While learning Haskell I came across this flipMaybe function:
flipMaybe :: [Maybe a] -> Maybe [a]
flipMaybe [] = Just []
flipMaybe (Nothing:xs) = Nothing
flipMaybe (Just x:xs) = case flipMaybe xs of
Nothing -> Nothing
Just ls -> Just (x:ls)
I can't wrap my head around the last line. What is ls
here? How does the recursion work here? Or in another words, can someone show me how this function solves flipMaybe [Just 1, Just 2, Just 3]
? (step by step)
CodePudding user response:
I can't wrap my head around the last line. What is
ls
here?
If the recursive call on the tail of the list return a Just ls
, then ls
is the list wrapped in the Just
. So if flipMaybe [Just 3]
is called, this will return a Just [3]
, and thus ls
is [3]
.
This is used to prepend the list with xs
. If we thus evaluate flipMaybe [Just 1, Just 2]
, then we first inspect the first item, if that is a Nothing
, we return Nothing
: we do not care about the rest of the list, we know that the outcome will be a Nothing
, if it is a Just …
, we should check what flipMaybe [Just 2]
will return. If it returns a Nothing
, then we thus return Nothing
, since then it means there is a Nothing
in the tail of the list. If it is a Just ls
, then we return a Just (x : ls)
, we thus prepend the item of the list to the outcome of the recursive call.
If the list thus looks like [Just 2, Nothing, Just 3]
, then we first investigate Just 2
, since it is not Nothing
, we make a recursive call with flipMaybe [Nothing, Just 3]
. Since that list starts with a Nothing
, Nothing
is returned from the flipMaybe [Nothing, Just 3]
, and thus we return Nothing
for flipMaybe [Just 2, Nothing, Just 3]
.