-
Notifications
You must be signed in to change notification settings - Fork 8
Maybe basics
Brian Marick edited this page May 19, 2017
·
4 revisions
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 -> NothingTwo 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
_ -> NothingNote: 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 -> []