Friday, 29 April 2016

Haskell: Higher order function

Higher order function
A function that takes other function as argument (or) returns a function as result (or) both is called higher order function.

For Example,
myMap:: (Integer -> Integer) -> [Integer] -> [Integer]
myMap fun [] = []
myMap fun (x:xs) = (fun x) : myMap fun xs

myMap function takes a function (Which takes an integer as input and return an integer as output), list of integers as arguments and applies the function on every element on the list. Following is the complete working example.


FunctionUtil.hs
myMap:: (Integer -> Integer) -> [Integer] -> [Integer]
myMap fun [] = []
myMap fun (x:xs) = (fun x) : myMap fun xs

doubleMe :: Integer -> Integer
doubleMe x = 2 * x

squareMe :: Integer -> Integer
squareMe x = x * x


*Main> :load FunctionUtil.hs
[1 of 1] Compiling Main             ( FunctionUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> myMap doubleMe [1, 2, 3, 4, 5]
[2,4,6,8,10]
*Main> 
*Main> myMap squareMe [1, 2, 3, 4, 5]
[1,4,9,16,25]
*Main> 


Convert list of integer code points to corresponding unicode character.
By using 'map chr list' we can convert list of integers to characters.

Prelude> :m Data.Char
Prelude Data.Char> 
Prelude Data.Char>  map chr [97..122]
"abcdefghijklmnopqrstuvwxyz"
Prelude Data.Char> 
Prelude Data.Char>  map chr [50..80]
"23456789:;<=>?@ABCDEFGHIJKLMNOP"


Convert list of characters to corresponding unicode points.
By using 'map ord list', we can covert list of characters to corresponding unicode points.

Prelude> :m Data.Char
Prelude Data.Char> 
Prelude Data.Char> map ord ['a' .. 'z']
[97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122]
Prelude Data.Char> 
Prelude Data.Char> map ord ['A' .. 'Z']
[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90]





Previous                                                 Next                                                 Home

No comments:

Post a Comment