Sunday 5 June 2016

Haskell: Return an element from list that satisfies given predicate


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

Prelude> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getElement even [1, 2, 3, 4, 5]
Just 2
*Main> getElement odd [ 2, 6, 3, 4, 5]
Just 3
*Main> getElement odd [ 2, 6]
Nothing
*Main> getElement odd []
Nothing
*Main> :t getElement
getElement :: (a -> Bool) -> [a] -> Maybe a


Previous                                                 Next                                                 Home

No comments:

Post a Comment