What is :-) ?
Julian Fondren
julian.fondren at gmail.com
Mon Nov 20 19:25:31 UTC 2023
On Monday, 20 November 2023 at 16:09:33 UTC, Antonio wrote:
> **Why this is a function and not a delegate?**
>
> ```auto createCounter = (int nextValue) => (int dummy) =>
> nextValue++;```
>
> Syntactically I dont see any difference:
`createCounter` is a function, and not a delegate, as it doesn't
close over any variables. It returns a delegate as the variable
`nextValue` is closed over. There's no difference in syntax. The
difference is however important as an environment must be
retained for the closed-over variables and passed along with the
pointer, making delegates both more expensive and incompatible
with function pointers on the C ABI. Note that `f` and `g` are
obviously not pointing to the same `nextValue`:
```d
auto createCounter = (int nextValue) => () => nextValue++;
void main() {
import std.stdio : writeln;
auto f = createCounter(5);
auto g = createCounter(0);
writeln(f()); // 5
writeln(g()); // 0
writeln(f()); // 6
writeln(g()); // 1
}
```
> What "breaks" my mind is that a compiler decision (treat a
> piece of code as function or delegate) is not completely
> transparent
D is trying to be convenient (by offering delegates at all, and
by making the syntax so light) while offering fine control (by
letting you distinguish between function pointers and delegates).
It'd be a much simpler language if it dropped one of those aims,
but such languages also already exist.
Similarly D also distinguishes between "numbers" (`int`) and
"numbers" (`double`) and this can also be transparent and also
cause 'side effects'. Someone educated in mathematics but not
familiar with computing might complain about
```d
void main() {
import std.stdio : writefln;
auto n = 1;
writefln!"%d"(n);
}
```
breaking when "all I did was bump n by one-tenth, to 1.1".
I'm not trying to be mean with this example, and I don't think
it's shameful either to know mathematics but not computing. But D
expects you to be familiar with such things for you to not be
surprised by how it behaves.
More information about the Digitalmars-d-learn
mailing list