On 2013-52-05 20:01, Michael Engelhardt <m...@mindcrime-ilab.de> wrote:
Hi,
just playing around with the functional capabilities of D. One concept
of the pure functional programming is that variables should not be
reassigned, so the best(?) way to assure this is using immutable:
immutable auto gen = sequence!("n");
immutable auto seq = take(gen,10);
immutable auto filtered = filter!("a % 3 == 0 || a % 5 ==0")(seq);
immutable auto sum = reduce!("a+b")(filtered);
but the last line gives a compiler error:
Error: template instance
std.algorithm.reduce!("a+b").reduce!(immutable(FilterResult!(unaryFun,immutable(Take!(immutable(Sequence!("n",Tuple!())))))))
error instantiating
It compiles and run as expected if I remove the immutable constraint on
the reduce expression. So what is happening here? I thought reduce will
create a new data structure containing the resulting values like filter
and other operations too? That seems not to be the case, maybe someone
could give me a deeper understanding of this.
The reason is that ranges may not be immutable or const.
Ranges need to be mutated (popFront) to be iterable, and your filtered
range cannot be mutated, by virtue of being immutable. I'm surprised that
seq and filtered work, but I guess there may be specializations that
circumvent the problem.
In other words, remove immutable from the first three lines, and the
program should compile.
A little details is that immutable auto is unnecessary, as immutable
implies auto (the details are more complex, but that's the short version).
--
Simen