Maybe identities

In the monoid lesson, we posed this question: If each of the following four functions is the (<>) operation for a semigroup, what is the identity value that makes it a monoid?

f3

f3 :: Semigroup a => Maybe a -> Maybe a -> Maybe a
f3 (Just x) (Just y) = Just (x <> y)
f3 _        _        = Nothing

Identity value: Just mempty

This one was slightly a trick question, because we have to strengthen the constraint on a from Semigroup to Monoid in order to ensure that this identity value exists.

Note that Nothing is not an identity for this function! Remember the identity laws. For all x:

  • mempty <> x = x
  • x <> mempty = x

Take, for example, x = Just 1. Then f3 Nothing (Just 1) is Nothing, not Just 1, therefore we know that Nothing is not an identity.

f4_first

f4_first :: Maybe a -> Maybe a -> Maybe a
f4_first (Just x) (Just y) = Just x
f4_first (Just x) Nothing  = Just x
f4_first Nothing  (Just y) = Just y
f4_first Nothing  Nothing  = Nothing

Identity value: Nothing

f4_last

f4_last :: Maybe a -> Maybe a -> Maybe a
f4_last (Just x) (Just y) = Just y
f4_last (Just x) Nothing  = Just x
f4_last Nothing  (Just y) = Just y
f4_last Nothing  Nothing  = Nothing

Identity value: Nothing

f4_both

f4_both :: Semigroup a => Maybe a -> Maybe a -> Maybe a
f4_both (Just x) (Just y) = Just (x <> y)
f4_both (Just x) Nothing  = Just x
f4_both Nothing  (Just y) = Just y
f4_both Nothing  Nothing  = Nothing

Identity value: Nothing

Join Type Classes for courses and projects to get you started and make you an expert in FP with Haskell.