Monday, 6 June 2016

Haskell: Get the first element of a list (or) string


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

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment