Curious thoughts, regarding functional programming
Jacob Carlborg
doob at me.com
Wed Oct 12 05:13:08 PDT 2011
On 2011-10-12 10:21, Gor Gyolchanyan wrote:
> I find myself constantly dreaming about a syntax sugar, which would
> make me (and probably, many others) very happy.
> An important and popular aspect of functional programming is the
> ability to pass delegate literals to functions.
> The downside to this is the ugliness of the resulting code, which
> discourages doing so:
> std.concurrency.spawn({ foreach(i, 0.100) { } });
> This piece of code has way too much punctuation. Worst of all, the
> entire delegate literal is crammed inside the function call
> parentheses.
> It looks especially ugly when the delegate literal is not a one-liner.
> The way I saw it in my dreams is:
>
> spawn()
> {
> foreach(i; 0..100) { }
> };
>
> What happened here is, that the delegate moved outside the parentheses.
> This looks awfully like a function definition, right?
> Wrong!
> This does not have a return type, the parameters are not definitions,
> they are values and there is a semicolon at the end (which quickly
> gives a visual clue of what this thing actually is).
> Hey, wait a minute! What about parameters to delegates and what about
> other delegate parameters?
> Well, this will work with only one delegate (or function) parameter
> and the parameters could be specified in a second set of parentheses
> (again this would look like a template, but it actually won't):
>
> spawn(5, 4, 65)(int x, int y, int z)
> {
> /*...*/
> };
>
> IMO, this looks WAY more beautiful, then what we have now.
> I don't see any reason why this would break existing code.
> I know, I know this is hard to implement and we got better things to do.
> I'm just saying. This would look good.
This has been proposed several times before. Something like, if a
function takes a delegate as its last parameter then this syntax would work:
void unless (bool condition, void delegate () dg)
{
if (condition)
dg();
}
unless(a == b)
{
// delegate
}
And passing arguments to the delegate:
foo(1 ; 2){}
Any arguments to the left of the semicolon would be passed to the
delegate. When this feature is talked about you usually want more
things, like, what I would like to call, "soft" and "hard" returns.
void iterate (int start, int end, void delegate (int a) dg)
{
foreach (a ; start .. end)
dg();
}
When this delegate is called you want to both be able to just return
from the delegate but also return from "foo".
iterate(1, 10 ; int a)
{
if (a == 2)
yield; // soft return, just returns from the delegate
else if (a == 4)
return; // hard return, return from both the delegate and the
function that called the delegate
}
Currently we only have "soft" returns from delegates.
--
/Jacob Carlborg
More information about the Digitalmars-d
mailing list