Monday 6 June 2016

Haskell: get last element of a list (or) string


listUtil.hs
getLastEle :: [a] -> Maybe a
getLastEle [] = Nothing
getLastEle (x:[]) = Just x
getLastEle (x:xs) = getLastEle xs

*Main> :load listutil.hs
[1 of 1] Compiling Main             ( listutil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getLastEle []
Nothing
*Main> 
*Main> getLastEle [1, 2, 3]
Just 3
*Main> 
*Main> getLastEle [[1, 2, 3], [2, 3], [4, 5], []]
Just []
*Main> 
*Main> getLastEle "Hare Ram"
Just 'm'
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment