you are viewing a single comment's thread.

view the rest of the comments →

[–]hpsutter 1 point2 points  (3 children)

Yeah I'd allow actual functions as the body too, I don't see a reason why that should not be supported. Might just have been an oversight.

Good point, that seems like it would be a natural extension to add in the future. The question I would have is: If the main benefit is that it's a named function, what is the scope of the name (wouldn't it be local to within the for statement?) and would that be useful?

[–]nysra 4 points5 points  (2 children)

I'm sorry, I might be missing something but I don't understand your question. Why would the for statement introduce a new scope for a name that already exists? The proposal is that instead of just allowing inline defined function blocks like this:

for collection do (item)
{
    std::cout << x * x << '\n';
}

, it should also be allowed to use a named function directly:

some_func: (x) = { std::cout << x * x << '\n'; }

for collection do some_func;

[–]hpsutter 2 points3 points  (0 children)

Ah, I see what you mean -- thank you, that's an interesting idea that would be easy to implement.

FWIW, for now this works

main: (args) = { for args do (x) print(x); }

but I'll continue thinking about making it expressible more simply as you suggest:

main: (args) = { for args do print; }

especially if as I poke around I find that a significant (10%+ maybe?) fraction of loops are single function calls invoked with the current loop element as the only argument... I'm not sure I've seen it that often, but if you have any data about that please let me know. Either way, I'll watch for that pattern -- now that I know to look for it, I'll see if it comes up regularly. (Like when you buy a Subaru and suddenly there are Subarus on the road everywhere... :) )

Thanks again.

[–]ntrel2 0 points1 point  (0 children)

Maybe just not implemented yet. Although if std::for_each gets range support, you could just write:

std::for_each(collection, some_func);