Sunday 5 June 2016

Haskell: Get all even numbers from list of integers


ListUtil.hs
getEvenNumbers :: [Integer] -> [Integer]
getEvenNumbers [] = []
getEvenNumbers (x:xs)
    | even x = x : getEvenNumbers xs
    | otherwise = getEvenNumbers xs

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getEvenNumbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0,2,4,6,8,10]
*Main> 
*Main> getEvenNumbers []
[]
*Main> 

We can rewrite the above program-using filter in a convenient way.

*Main> :t filter
filter :: (a -> Bool) -> [a] -> [a]


Observe the signature of filter, it takes a function, list of elements of type ‘a’ as input and apply the function on list of elements and return new list of elements that satisfy given function (a -> Bool).
*Main> filter even [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0,2,4,6,8,10]
*Main> 
*Main> filter even []
[]
*Main>



Previous                                                 Next                                                 Home

No comments:

Post a Comment