Sunday 5 June 2016

Haskell: Get index of element in the list


IndexUtil.hs
getElementIndex :: (Eq a) => a -> [a] -> Maybe Int
getElementIndex ele [] = Nothing
getElementIndex ele xs = getIndex ele xs 0

getIndex :: (Eq a) => a -> [a] -> Int -> Maybe Int
getIndex ele [] index = Nothing
getIndex ele (x:xs) index
    | (ele == x) = Just index
    | otherwise = getIndex ele xs (index+1)

*Main> :load IndexUtil.hs
[1 of 1] Compiling Main             ( IndexUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getElementIndex 10 []
Nothing
*Main> 
*Main> getElementIndex 10 [2, 3, 5, 7, 10, 9, 10, 19, 81]
Just 4
*Main> getElementIndex 'H' "Good Bye"
Nothing
*Main> 
*Main> getElementIndex 'H' "Good Bye Hari"
Just 9
*Main> 



Previous                                                 Next                                                 Home

No comments:

Post a Comment