Pure functions in D

bearophile bearophileHUGS at lycos.com
Mon Sep 22 04:56:12 PDT 2008


Walter:
> http://www.reddit.com/r/programming/comments/72r6q/walter_bright_pure_functions_in_d/

It's an interesting read, a little refinement of things we have already started discussing.


This page shows that gcc too has the "pure" attribute, for the same purpose (but the GCC compiler has to trust the programmer much more):
http://gcc.gnu.org/onlinedocs/gcc-4.3.0//gcc/Function-Attributes.html


>(Invariant means immutable.)<

This specification, near the top of the article, that tells that a word means something else is a WARNING SIGN large as a wall that tells that that name is wrong and it has to change. Now I think D2 will sooner of later have to use the "immutable" word instead, as Python and Java communities too use.


>Parameters to a pure function can be mutable, but calls cannot be cached or executed asynchronously if the arguments contain any references to mutable data.<

I don't understand how can such function be pure.


>A pure function can throw an exception (purity does not imply nothrow).<

At the moment I think this the trickier decision of the whole pure stuff. This has to be chosen wisely, because a function that can throw isn't really pure. The situation is messy. It may be better for pure functions to never throw exceptions... This topic needs more thinking, with the help from the people of the functional crowd (Lambda the Ultimate) because otherwise there's a high risk of creating half-baked stuff as the closures in D2 (lot of people want a way to not allocate data on the heap. I think this can be solved making them allocate data on the heap by default, unless the programmer explicitly chooses otherwise, for example adding a "scope" statement before the closure).


int x = foo(3) + bar[foo(3)];
need only execute foo(3) once.

If foo can throw exceptions that's not true anymore, I think.


>They can be hot swapped (meaning replaced at runtime), because they do not rely on any global initialization or termination state.<

This sounds true and interesting, but what can it be used/useful for?

-----------

Bill Baxter:
>Glad to see that "const" args will be OK for pure functions, too. Not just "invariant" as was originally announced. That will certainly make pure functions in D much more useful.<

I don't understand (probably because I don't remember what 'const' exactly means here).


millstone:
>Also, what if a parameter to a pure function is marked lazy?<

Interesting question. I think the lazy callable can be accepted (at compile time) only if it wraps an immutable value or a pure function.

Bye,
bearophile



More information about the Digitalmars-d mailing list