m (Fix link)
(fixed dead link)
|(One intermediate revision by one user not shown)|
|Line 45:||Line 45:|
* The [http://haskell.cs.yale.edu/tutorial/functions.html Functions section] in the Gentle Introduction.
* The [http://www.haskell.org/tutorial/functions.html Functions section] in the Gentle Introduction.
Latest revision as of 17:28, 10 November 2011
Mathematically speaking, a function relates all values in a set A to values in a set B. The function , given that x is an integer, will map all elements of the set of integers into another set -- in this case the set of square integers. In Haskell functions can be specified as below in the examples, with an optional type specification that gives the compiler (and other programmers) a hint as to the use of the function.
 1 Examples
square :: Int -> Int square x = x * x
In other words, a function has input and output, and it describes how to produce the output from its input. Functions can be applied, which just means that you give an input value as argument to the function and can then expect to receive the corresponding output value.
Haskell functions are first class entities, which means that they
- can be given names
- can be the value of some expression
- can be members of a list
- can be elements of a tuple
- can be passed as parameters to a function
- can be returned from a function as a result
(quoted from Davie's Introduction to Functional Programming Systems using Haskell.)
 1.1 map example
As an example of the power of first-class functions, consider the function map:
map :: (a -> b) -> [a] -> [b] map f xs = [f x | x <- xs]
(Note this is a Higher order function.)This function takes two arguments: a function f which maps as to bs, and a list xs of as. It returns a list of bs which are the results of applying f to every member of xs. So
 1.2 Composition / folding example
Haskell supports a Function composition operator:
(.) :: (b -> c) -> (a ->b) -> (a->c) (f . g) x = f (g x)
newSet = (foldr1 (.) (map insert myList)) mySet
will define newSet as mySet with the elements of myList inserted.
 2 See also
- The Functions section in the Gentle Introduction.