Sunday, 5 June 2016

Haskell: Implement map function

map’ function takes a function and list as inputs and applies the function to every element of the list.

Prelude> :t map
map :: (a -> b) -> [a] -> [b]

Observe above signature, map function takes two arguments; one is a function and other is list. The function (a -> b) takes an input of type a and apply some operation on the data and convert it to type b.

Following is the implementation of map function.


MapUtil.hs
myMap :: (a -> b) -> [a] -> [b]
myMap fun [] = []
myMap fun (x:xs) = (fun x) : (myMap fun xs)

Prelude> :load MapUtil.hs
[1 of 1] Compiling Main             ( MapUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> let square x = (x*x)
*Main> 
*Main> myMap square []
[]
*Main> myMap square [2, 3, 5, 7]
[4,9,25,49]
*Main> 
*Main>


Previous                                                 Next                                                 Home

No comments:

Post a Comment