Skip to content
Brian Marick edited this page May 19, 2017 · 4 revisions

Full source

Problem 1

toBool : Maybe a -> Bool
toBool maybe =
  case maybe of
    Just _ -> True
    Nothing -> False

_ is a name that matches anything but also signals that you won't be using the value. It's more than a convention: the compiler will complain if you try.

Problem 2

This case shows that patterns can be deeply nested.

join : Maybe (Maybe a) -> Maybe a
join nesting =
  case nesting of
    Just (Just wrapped) -> Just wrapped
    Just Nothing -> Nothing
    Nothing -> Nothing

Two of the cases produce Nothing. That suggests replacing the exact patterns with a "catch-all" pattern:

join2 : Maybe (Maybe a) -> Maybe a
join2 nesting =
  case nesting of
    Just (Just wrapped) -> Just wrapped
    _ -> Nothing

Note: you wouldn't have to use _. You could use a variable like otherwise. That wouldn't be idiomatic, though.

You can't apply this function to Just 3 because that's of type Maybe a, not Maybe (Maybe a).

Problem 3

toList : Maybe a -> List a         
toList maybe = 
  case maybe of
    Just wrapped -> [wrapped]
    Nothing -> []

Clone this wiki locally