Friday, 29 April 2016

Haskell: map function

map function list
Apply function to every item of list and return a list of the results.

Suppose you had a list of elements, you want to perform following operations.
a.   Increment every element of list by 1
b.   Twice every element in the list
c.    Convert all negative values in the list to positive


mapEx.hs
{- Increment every element of list by 1 -}
addBy1 :: [Integer] -> [Integer]
addBy1 [] = []
addBy1 (x:xs) = (x+1): addBy1 xs

{- Twice every element in the list -}
twiceAll :: [Integer] -> [Integer]
twiceAll [] = []
twiceAll (x:xs) = (2*x) : twiceAll xs

{- Convert all negative values in the list to positive -}
absAll :: [Integer] -> [Integer]
absAll [] = []
absAll (x:xs) = abs (x) : absAll xs

Prelude> :load mapEx.hs
[1 of 1] Compiling Main             ( mapEx.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> addBy1 [2, 3, 5, 7, -2, -3, -5, -7]
[3,4,6,8,-1,-2,-4,-6]
*Main> 
*Main> twiceAll [2, 3, 5, 7, -2, -3, -5, -7]
[4,6,10,14,-4,-6,-10,-14]
*Main> 
*Main> absAll [2, 3, 5, 7, -2, -3, -5, -7]
[2,3,5,7,2,3,5,7]
*Main> 

As you observe, all the above functions look similar, don't you think we are repeating same flow in all the three functions. There should be some way, so we don’t have to repeat the same logic. By using map function, we can rewrite above program like below.


mapEx.hs
{- Increment every element of list by 1 -}
addBy1 :: [Integer] -> [Integer]
addBy1 xs = map (1+) xs

{- Twice every element in the list -}
twiceAll :: [Integer] -> [Integer]
twiceAll xs = map (2*) xs

{- Convert all negative values in the list to positive -}
absAll :: [Integer] -> [Integer]
absAll xs = map abs xs


Sections
Sections are a convenient syntax for partial application of binary operator. Sections are written as (operator e) or ( e operator), where operator is a binary operator and e is an expression. For a section, we only give one of the arguments to the infix operator, and it represents a function, which intuitively takes an argument and puts it on the "missing" side of the infix operator.
*Main> map (2+) [2, 3, 5, 7]
[4,5,7,9]
*Main> 
*Main> map (*3) [2, 3, 5, 7]
[6,9,15,21]
*Main> 
*Main> map (/3) [2, 3, 5, 7]
[0.6666666666666666,1.0,1.6666666666666667,2.3333333333333335]

In above snippet (+2), (*3), (/3) are functions.



Previous                                                 Next                                                 Home

No comments:

Post a Comment