## Friday, January 11, 2008

### Redefining functional composition in haskell

For those us that haven't done calculus or differential equations in a while, visualizing functional composition in functional languages like haskell may be difficult. So here are some practical examples for really visualizing composition. The wikipedia definition for function composition in a computer science context has the following: "function composition is an act or mechanism to combine simple functions to build more complicated ones."

In math 101, we learned the following:

given the value of 'x', pass 'x' to the function g and then the result of g of x to the function f to get a result.

f(g(x))

Let's say we are doing the following calculation:

y = g(x) = 2 * x
z = f(y) = 3 * y
z is our result.

If we provide an input of 4, we have the following.

y = 2 * 4 = 8
z = 3 * 2 * 4 = 24
z = 3 * g(x where x = 4) = 24

How would you do this in haskell (in prelude):

Open ghci:

First, here is the function definition for function composition:
(.) :: (b -> c) -> (a -> b) -> a -> c

Prelude> let ggg x = 2 * x
Prelude> let fff y = 3 * y
Prelude> (fff . ggg) 4
24 (our result)

Or ((fff . ggg) 4)

Now, let's define this this in a new haskell source file:
`module Main where-- x -> yggg :: Integer -> Integerggg x = 2 * x-- y -> zfff :: Integer -> Integerfff y = 3 * y-- x -> zcompose :: Integer -> Integercompose x = (fff . ggg) xmain = do    putStrLn \$ "Z Result should be 24=" ++ show (compose 4)`

#### 1 comment:

CresceNet said...

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my site, it is about the CresceNet, I hope you enjoy. The address is http://www.provedorcrescenet.com . A hug.