Sunday, 5 June 2016

Haskell: Get all odd numbers from list of integers

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

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getOddNumbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1,3,5,7,9]
*Main> 
*Main> getOddNumbers []
[]
*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 odd [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1,3,5,7,9]
*Main> 
*Main> filter odd []
[]



Previous                                                 Next                                                 Home

1 comment: