Skip to content

Latest commit

 

History

History
36 lines (27 loc) · 1.05 KB

27.md

File metadata and controls

36 lines (27 loc) · 1.05 KB

Lambda functions

Lambda functions are anonymous functions. When you need a small function and you do not want to create a separate declaration, a lambda function might be the best choice.

Let's have a look at a few examples.

\x -> x + 2
\x y -> x + y

The slash character resembles lambda. Between lambda and "->" are the function parameters, after that is the function body. You can use lambda functions everywhere where you would use a function.

map (\x -> if even x then "even" else "odd") [1..10]

Exercise

  • Read a line from standard input and write out the length of each word in order. Try to use lambda functions and higher order functions.
Please enter a line: this is a line
[4, 2, 1, 4]
  • Try to print out the result using mapM_ or traverse. First have a look at their type signature. If it looks intimidating try to replace type constructors with IO and [].

  • Rewrite at least three old exercises to use lambda functions instead of writing separate named functions.