Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
First-class function
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Non-local variables and closures === {{further information|Non-local variable|Closure (computer science)}} Once we have anonymous or nested functions, it becomes natural for them to refer to variables outside of their body (called ''non-local variables''): <syntaxhighlight lang="haskell"> main = let a = 3 b = 1 in map (\x -> a * x + b) [1, 2, 3, 4, 5] </syntaxhighlight> If functions are represented with bare function pointers, we can not know anymore how the value that is outside of the function's body should be passed to it, and because of that a closure needs to be built manually. Therefore we can not speak of "first-class" functions here. <syntaxhighlight lang="c"> typedef struct { int (*f)(int, int, int); int a; int b; } closure_t; void map(closure_t *closure, int x[], size_t n) { for (int i = 0; i < n; ++i) x[i] = (closure->f)(closure->a, closure->b, x[i]); } int f(int a, int b, int x) { return a * x + b; } void main() { int l[] = {1, 2, 3, 4, 5}; int a = 3; int b = 1; closure_t closure = {f, a, b}; map(&closure, l, 5); } </syntaxhighlight> Also note that the <code>map</code> is now specialized to functions referring to two <code>int</code>s outside of their environment. This can be set up more generally, but requires more [[boilerplate code]]. If <code>f</code> would have been a [[nested function]] we would still have run into the same problem and this is the reason they are not supported in C.<ref>"If you try to call the nested function through its address after the containing function has exited, all hell will break loose." ([https://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Nested-Functions.html#Nested-Functions GNU Compiler Collection: Nested Functions])</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)