Sunday, 5 June 2016

Haskell: Square every element of a loop


square.hs
squareList :: [Integer] -> [Integer]
squareList [] = []
squareList (x:xs) = (x*x) : squareList xs

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


We can rewrite the above functionality using map function like below. ‘map’ function takes a function and list as inputs and applies the function to every element of the list.
*Main> let square x = (x*x)
*Main> let squareList xs = map square xs
*Main> 
*Main> squareList []
[]
*Main> squareList [2, 3, 5, 7]
[4,9,25,49]
*Main>



Previous                                                 Next                                                 Home

No comments:

Post a Comment