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

In Haskell

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 -> y
ggg :: Integer -> Integer
ggg x = 2 * x

-- y -> z
fff :: Integer -> Integer
fff y = 3 * y

-- x -> z
compose :: Integer -> Integer
compose x = (fff . ggg) x

main = do
putStrLn $ "Z Result should be 24=" ++ show (compose 4)

No comments: