Saturday, 30 April 2016

Haskell: composition of functions


In Haskell, one function output can be passed as input to other function. Combining functions by passing output of one function as input to other function is called composition of functions.

For example,
Let g(x) = 2x, f(x) = x + 1
then
f(g(x)) = f(2x) = 2x + 1
g(f(x)) = g(x+1) = 2 (x+1) = 2x + 2

Lets implement above example in Haskell.

function_composition.hs
f x = x + 1
g x = 2 * x

*Main> :load function_composition.hs
[1 of 1] Compiling Main             ( function_composition.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> f 5
6
*Main> g 5
10
*Main> 
*Main> f (g 5)
11
*Main> g (f 5)
12

  Function composition operator (.)
We can compose functions using ‘.’ Operator.

For example,
fOfgOfx x = (f . g) x
gOffOfx x = (g . f) x

(f . g) x is equivalent to f(g x), (g . f) x is equivalent to g(f x).

function_composition.hs
f x = x + 1
g x = 2 * x

fOfgOfx x = (f . g) x
gOffOfx x = (g . f) x

Prelude> :load function_composition.hs
[1 of 1] Compiling Main             ( function_composition.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> fOfgOfx 5
11
*Main> gOffOfx 5
12x


fOfgOfx x = (f . g) x can be written like fOfgOfx  = (f . g)  (I just omitted the input argument x).

function_composition.hs
f x = x + 1
g x = 2 * x

fOfgOfx  = (f . g)
gOffOfx  = (g . f)

*Main> :load function_composition.hs
[1 of 1] Compiling Main             ( function_composition.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> fOfgOfx 5
11
*Main> gOffOfx 5
12



Previous                                                 Next                                                 Home

No comments:

Post a Comment