Functional Programming with D
Ali Çehreli
acehreli at yahoo.com
Sat Apr 13 17:38:24 PDT 2013
On 04/13/2013 05:29 AM, qznc wrote:
> I wrote a small article to summarize D's suitability for functional
> programming.
>
> http://beza1e1.tuxen.de/articles/functional_D.html
>
> Feedback welcome! :)
>
Nice article; thanks. :)
Some quotes from the article and some notes:
1) "can qualify variables as immutable, which is similiar to C's const"
D's immutable is similar to C's const only when we are talking about values:
const int c_i = 42; // in C
immutable d_i = 42; // in D
When it is a reference though, not immutable but D's const is similar to
C's const. Otherwise, there is the following difference:
// in C: I have no idea whether c is immutable
void foo(const int * c);
// in D: I know d is immutable
void foo(immutable const ref d);
(Actually, not only I "know", but I "demand" that d is immutable.)
2) "if you have a function which does not mutate an argument, then
qualify it const, but not immutable"
I had arrived the same conclusion (and have been spreading it too :)).
Actually, the choice is not that clear: If the function is going to need
an immutable copy of a reference parameter anyway, then it is better
that it goes ahead and takes an immutable reference parameter:
void foo(immutable(int)[] numbers);
The benefit is, if the caller already has an immutable slice, then that
slice gets passed as the argument. That is the fastest... On the other
hande, if the caller does not have an immutable slice, then the caller
makes one and passes the new copy. Nothing is lost: The copy that the
function would have to make has been made by caller.
Although that seems like an implementation detail of the function
leaking out, and it really is, it is not that bad if we view it like
this: What is happening is that the function is working with its caller
to get more performance.
3) "D does not allow you to cast something to immutable"
I think you mean "no implicit conversion" because it is not true if we
take what you said literally:
auto a = [ 1, 2 ];
immutable i = cast(immutable)a; // dangerous
a[0] = 42;
assert(i[0] == 42); // oops: immutable element has changed!
Ali
More information about the Digitalmars-d-announce
mailing list