Sujet : Re: technology discussion → does the world need a "new" C ?
De : ben (at) *nospam* bsb.me.uk (Ben Bacarisse)
Groupes : comp.lang.cDate : 11. Jul 2024, 11:56:25
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <874j8wkxie.fsf@bsb.me.uk>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
User-Agent : Gnus/5.13 (Gnus v5.13)
Michael S <
already5chosen@yahoo.com> writes:
On Thu, 11 Jul 2024 08:41:14 -0000 (UTC)
Kaz Kylheku <643-408-1753@kylheku.com> wrote:
...
First class functions could do something like this:
// multiplier takes a coefficient and returns a pointer to
// function
int (*multiplier(int coefficient))(int) {
// fantasy lambda syntax. Return type int is written after
// parameter list.
return lambda(int x) int {
return coefficient * x;
}
}
int (*doubler)(int) = multiplier(2);
int x = doubler(42); // x becomes 84
Even though the lambda is returned out of multiplier, whose execution
terminates, when the returned function is invoked, it can refer to the
coefficient, which is captured in a lexical closure.
With a C-like typedef, we can declutter the definition of mutiplier:
typedef int (*int_int_fn)(int);
int_int_fn multiplier(int coefficient) {
return lambda(int x) int {
return coefficient * x;
}
}
>
Thank you.
Your example confirms my suspicion that the difference between first
and second class of functions doesn't become material until language
supports closures.
That's half true, but it concentrates on something that is partly
syntactic -- the lexical binding of names. It possible to do the same
things with no names in sight so the term "closure" would seem rather
odd. For example, Kaz's example could be written like this is Haskell:
$ ghci
GHCi, version 9.4.7:
https://www.haskell.org/ghc/ :? for help
ghci> multiplier = (*)
ghci> doubler = multiplier 2
ghci> doubler 42
84
and, indeed, one way to implement Haskell is is to tranform the code
into combinators. Combinators were first studied by logicians like
Haskell Curry as a way to re-write formal logics that use quantifiers
(which bind names) into nameless forms.
Of course, "something" is mysteriously doing the same work as the
closures in Kaz's examples, but it not using lexical binding to it.
-- Ben.