Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell function composition

I am reading this tutorial on Haskell. They define function composition as the following:

(.)                     :: (b->c) -> (a->b) -> (a->c) f . g                   = \ x -> f (g x) 

No examples were provided, which I believe would enlighten me as to what is being defined here.

Can someone provide a simple example (with explanation) of how function composition is used?

like image 341
Fragsworth Avatar asked Sep 25 '09 07:09

Fragsworth


People also ask

What is higher order function in Haskell?

A higher-order function is a function that takes other functions as arguments or returns a function as result.

What is dollar Haskell?

The dollar sign, $ , is a controversial little Haskell operator. Semantically, it doesn't mean much, and its type signature doesn't give you a hint of why it should be used as often as it is. It is best understood not via its type but via its precedence.

What is Dot in Haskell?

The dot ( . ) is the Haskell operator for function composition. Function composition comes from mathematics but actually, it can be really useful to make music. Haskell was originally designed by mathematicians and computer magicians. Its syntax borrowed quite a lot from mathematical notation.

What does the operator do in Haskell?

Haskell provides special syntax to support infix notation. An operator is a function that can be applied using infix syntax (Section 3.4), or partially applied using a section (Section 3.5).


1 Answers

Function composition is a way to "compose" two functions together into a single function. Here's an example:

Say you have these functions:

even :: Int -> Bool not :: Bool -> Bool 

and you want to define your own myOdd :: Int -> Bool function using the two above.

The obvious way to do this is the following:

myOdd :: Int -> Bool myOdd x = not (even x) 

But this can be done more succinctly using function composition:

myOdd :: Int -> Bool myOdd = not . even 

The myOdd functions behave exactly the same, but the second one is created by "glue-ing" two functions together.

A scenario where this is especially useful is to remove the need for an explicit lambda. E.g:

map (\x -> not (even x)) [1..9] 

can be rewritten to:

map (not . even) [1..9] 

A bit shorter, less room for errors.

like image 143
Tom Lokhorst Avatar answered Sep 22 '22 22:09

Tom Lokhorst