Sunday 5 June 2016

Haskell: Implement filter function

‘filter’ function 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> :t filter
filter :: (a -> Bool) -> [a] -> [a]


FilterUtil.hs
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter _ [] = []
myFilter fun (x:xs)
    | fun x = x : myFilter fun xs
    | otherwise = myFilter fun xs

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment