Using pure to create immutable
Jesse Phillips
jessekphillips+D at gmail.com
Thu Sep 22 11:53:46 PDT 2011
The discussion on Reddit brought to my attention that pure functions can return and assign to an immutable.
http://www.reddit.com/r/programming/comments/knn5p/thoughts_on_immutability_in_d/c2lsgek
I am trying to modify the example request to make use of this, but have failed.
http://www.reddit.com/r/programming/comments/knn5p/thoughts_on_immutability_in_d/c2lrfpm
test.d(4): Error: cannot implicitly convert expression (makeFromArray([1,2,3]))
of type test.List!(int).List to immutable(List)
Is this a bug? I can't identify where this issue would lie (works with inheritance and templating).
void main() {
immutable a = makeFromArray([1,2,3]);
}
private abstract class List(T) {
abstract bool isEmpty () const;
abstract T head () const;
abstract const(List!T) tail () const;
}
private final class Cons(T): List!T {
immutable T head_;
Cons!T tail_; // not immutable here for a reason
this(T h, Cons!T t) { head_ = h; tail_ = t; }
override bool isEmpty() const { return false; }
override T head () const { return head_; }
override const(Cons!T) tail () const { return tail_; }
}
List!T makeFromArray(T)(T[] array) pure {
if (array.length == 0) { return null; }
auto result = new Cons!T(array[0], null);
auto end = result;
for (int i = 1; i < array.length; ++i) {
end.tail_ = new Cons!T(array[i], null);
end = end.tail_;
}
return result;
}
More information about the Digitalmars-d-learn
mailing list