Functional programming in D and some reflexion on the () optionality.
Christophe Travert
travert at phare.normalesup.org
Mon Aug 6 10:20:41 PDT 2012
deadalnix:
> The same way, the difference between a delegate and an expression don't
> exist anymore.
int fun();
int fun(int t);
One solution would be to find a way that would enable fun to be both a
function and its return type, and that would enable 1.fun to be both
delegate and its return type.
This can be achieved by implicit casting. The type of expression fun is
int function(), but if an int is expected, execute fun and use its
return value. Like:
struct Function
{
int fun();
alias fun this;
}
One difference with current behavior would be that "fun;" alone doesn't
actually execute the function. Statements consisting of a single
function parameterless expression could be made to call the function,
although I don't think this is a good idea because it would be an
exception in the previous rule, and parenthesis-less call is more a
functionnal programming feature, and should IMHO not be used when
side-effect is desired.
Also, in:
auto bar = fun;
bar is of type int function(), and not of type int. If the function is
pure, it doesn't make great difference, but if the function is impure,
then if is called each time bar is present in an expression that
requires an int.
The same way, the dot operator on a single parameter free or member
function would return a delegate, that is implicitely cast to its return
value if the return type is expected.
This would break code where the use of parenthesis-less function call is
hazardous, but hopefully not so much when it is legitimate [1].
What do you think?
--
Christophe
[1] templates will have to be taken care of: "a.map!(x=>x+1).array"
would try to instanciate array with a delegate type, whereas it should
be instanciated with a range type. From an the discussion about template
on enum type in this newsgroup, there is some opposition to make
template instanciate after an implicit cast because of the mess that can
arise and the technical difficulties for the compiler. However, if this
feature is limitted and controled, I think it can be worth it.
More information about the Digitalmars-d
mailing list