Sunday 5 June 2016

Haskell: get all the indexes of given element in the list


ListUtil.hs
getAllIndices :: (Eq a) => a -> [a] -> [Int]
getAllIndices _ [] = []
getAllIndices ele xs = getIndices ele xs 0


getIndices :: (Eq a) => a -> [a] -> Int -> [Int]
getIndices ele [] index = []
getIndices ele (x:xs) index
    | (ele == x) = index : getIndices ele xs (index+1)
    | otherwise = getIndices ele xs (index+1)

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getAllIndices 1 [2, 3, 5, 1, 3, 2, 1, 5, 6]
[3,6]
*Main> getAllIndices 'o' "Hello PTR, How are you"
[4,12,20]
*Main> getAllIndices 1 []
[]
*Main> :t getAllIndices
getAllIndices :: Eq a => a -> [a] -> [Int]
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment