Monday 6 June 2016

Haskell: Return all the elements of a list except the last one.


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

initEle :: [a] -> [a]
initEle (x:[]) = []
initEle (x:xs) = x: initEle (xs)

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment