Skip to content

Maybe

Remember, Maybe is a container with zero or one element. If the container is empty, foldl should return its initial accumulator value. If it isn't, then we need to combine the element in the container with the initial accumulator value to obtain the final result. This gives

instance Foldable Maybe where
    foldl f init = go
      where
        go Nothing  = init
        go (Just x) = f init x

Alternatively, we can provide a definition via foldMap. This needs to return mempty for the empty container, and the result of applying the given function to the only element in the container if its not empty:

instance Foldable Maybe where
    foldMap _ Nothing  = mempty
    foldMap f (Just x) = f x