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!
=== Higher-order functions: passing functions as arguments === {{further information|Higher-order function}} In languages where functions are first-class citizens, functions can be passed as arguments to other functions in the same way as other values (a function taking another function as argument is called a higher-order function). In the language [[Haskell (programming language)|Haskell]]: <syntaxhighlight lang="haskell"> map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x : map f xs </syntaxhighlight> Languages where functions are not first-class often still allow one to write higher-order functions through the use of features such as [[function pointer]]s or [[Delegate (CLI)|delegate]]s. In the language [[C (programming language)|C]]: <syntaxhighlight lang="c"> void map(int (*f)(int), int x[], size_t n) { for (int i = 0; i < n; i++) x[i] = f(x[i]); } </syntaxhighlight> There are a number of differences between the two approaches that are ''not'' directly related to the support of first-class functions. The Haskell sample operates on [[List (computing)|list]]s, while the C sample operates on [[Array data structure|arrays]]. Both are the most natural compound data structures in the respective languages and making the C sample operate on linked lists would have made it unnecessarily complex. This also accounts for the fact that the C function needs an additional parameter (giving the size of the array.) The C function updates the array [[in-place]], returning no value, whereas in Haskell data structures are [[persistent data structure|persistent]] (a new list is returned while the old is left intact.) The Haskell sample uses [[recursion]] to traverse the list, while the C sample uses [[iteration]]. Again, this is the most natural way to express this function in both languages, but the Haskell sample could easily have been expressed in terms of a [[fold (higher-order function)|fold]] and the C sample in terms of recursion. Finally, the Haskell function has a [[Polymorphism (computer science)|polymorphic]] type, as this is not supported by C we have fixed all type variables to the type constant <code>int</code>.
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)