Difference between revisions of "Anonymous function"

From HaskellWiki
Jump to navigation Jump to search
(HaWiki conversion)
 
(Fixed the Haskell tutorial link)
(2 intermediate revisions by 2 users not shown)
Line 3: Line 3:
   
   
An anonymous function is a [[Function]] without a name. It is a [[Lambda abstraction]] and might look like this: <hask>\x -> x + 1</hask>. (That backslash is supposed to look like a Lambda.)
+
An anonymous function is a [[function]] without a name. It is a [[Lambda abstraction]] and might look like this: <hask>\x -> x + 1</hask>. (That backslash is Haskell's way of expressing a &lambda; and is supposed to look like a Lambda.)
   
 
==Examples==
 
==Examples==
Line 43: Line 43:
 
addOneList' lst = map (\x -> x + 1) lst
 
addOneList' lst = map (\x -> x + 1) lst
 
</haskell>
 
</haskell>
  +
For completeness it's worth mentioning that this could be better written:
+
For completeness it's worth mentioning that this could be better written
  +
using a [[section]], in [[pointfree]] style:
   
 
<haskell>
 
<haskell>
Line 50: Line 52:
   
 
==See also==
 
==See also==
* Section 3.1 in the [http://haskell.cs.yale.edu/tutorial/functions.html Haskell tutorial].
+
* Section 3.1 in the [http://www.haskell.org/tutorial/functions.html Haskell tutorial].
 
* [[Closure]]
 
* [[Closure]]
 
* [[Lambda calculus]]
 
* [[Lambda calculus]]
  +
* [[Beta reduction]]

Revision as of 22:24, 21 December 2011



An anonymous function is a function without a name. It is a Lambda abstraction and might look like this: \x -> x + 1. (That backslash is Haskell's way of expressing a λ and is supposed to look like a Lambda.)

Examples

That is a nameless function which increments its parameter, x. So in Hugs or GHCi, I might say:

Prompt> (\x -> x + 1) 4
5 :: Integer

Or I could make a nameless function of two parameters, x and y: \x y -> x + y, which could be applied like so:

Prompt> (\x y -> x + y) 3 5
8 :: Integer

You could also name a lambda expression if you wanted to for some reason:

addOne = \x -> x + 1

Of course, there are a variety of better ways to write that in Haskell, but you get the idea.

But why bother?

Sometimes it is more convenient to use a lambda expression rather than giving a function a name. This is often the case when using map and foldl / foldr. So if I wanted to add one to each element of a list, here's one way to do it (without anonymous functions):

addOneList lst = map addOne' lst
  where addOne' x = x + 1

But here's another way, where we pass the anonymous function into map rather than any named function.

addOneList' lst = map (\x -> x + 1) lst

For completeness it's worth mentioning that this could be better written using a section, in pointfree style:

addOneList'' = map (+1)

See also