Sunday, 5 June 2016

Haskell: Get all indexes of elements in list that satisfies given predicate


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

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment