Search code examples
listhaskellrecursionoption-type

How to recursively iterate over a list with Maybe objects in Haskell


I am trying to create a function justifyList that takes a list of Maybe objects ([Maybe a]) and return a list of all objects of Just type, discarding any element that is Nothing in the parameter list.

My solution for now is

justifyList :: [Maybe a] -> [a]
justifyList [] = []
justifyList (x:xs) 
    | (isNothing x) = justifyList xs
    | otherwise = x : justifyList xs

where I try to recursively iterate through the parameter list and recursively put the current element x to the returned list [a], if it is of Just type.

However when interpreting a type mismatch error is generated

Couldn't match type a with Maybe a

Hence my question is; how do I recursively iterate through a list of Maybe objects? If this solution is sufficient, how do I convert xs to be of Maybe type?


Solution

  • Such function already lives in the Data.Maybe module and is named catMaybes :: [Maybe a] -> [a].

    You can implement this with recursion, but it might be more elegant to do this with list comprehension, since this allows us to effectively pattern match and unwrap at the same time, so:

    justifyList :: [Maybe a] -> [a]
    justifyList xs = [ x | Just x <- xs ]

    only for items that satisfy the Just x pattern, it will yield an item, so Just x <- xs performs a filtering as well.