Sunday, 5 June 2016

Haskell: Return all the elements from list that satisfies given predicate


ListUtil.hs
getElements :: (a -> Bool) -> [a] ->  [a]
getElements predicateFun list =  myFilter predicateFun list
    
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter p [] = []
myFilter p (x:xs)
    | p x = x:myFilter p xs
    | otherwise = myFilter p xs

*Main> :load listUtil.hs
[1 of 1] Compiling Main             ( listUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getElements odd [2, 3, 5, 4, 6, 17, 19]
[3,5,17,19]
*Main> 
*Main> getElements even [2, 3, 5, 4, 6, 17, 19]
[2,4,6]
*Main> 
*Main> getElements even []
[]
*Main>


Previous                                                 Next                                                 Home

No comments:

Post a Comment