Sunday, 5 June 2016

Haskell: Get index of element that satisfies given predicate


ListUtil.hs
getIndex :: (a -> Bool) -> [a] ->  Maybe Int
getIndex predicateFun list =  myFilter predicateFun list 0
    
myFilter :: (a -> Bool) -> [a] -> Int -> Maybe Int
myFilter _ [] _= Nothing
myFilter p (x:xs) index
    | p x = Just index
    | otherwise = myFilter p xs (index+1)

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment