on 63243ca help sign in
elk/libraries/Maybe.elm
47 lines 1.0 kB history raw
1module Maybe where
3{-| Represents an optional value. Maybe it is there, maybe it is not.
5# Type and Constructors
6@docs Maybe
8# Taking Maybes apart
9@docs maybe, isJust, isNothing
11# Maybes and Lists
12@docs justs
13-}
15import Basics (not, (.))
16import List (foldr)
18{-| The Maybe datatype. Useful when a computation may or may not
19result in a value (e.g. logarithm is defined only for positive
20numbers).
21-}
22data Maybe a = Just a | Nothing
24{-| Apply a function to the contents of a `Maybe`.
25Return default when given `Nothing`.
26-}
27maybe : b -> (a -> b) -> Maybe a -> b
28maybe b f m = case m of
29 Just v -> f v
30 Nothing -> b
32{-| Check if constructed with `Just`.
33-}
34isJust : Maybe a -> Bool
35isJust = maybe False (\_ -> True)
37{-| Check if constructed with `Nothing`.
38-}
39isNothing : Maybe a -> Bool
40isNothing = not . isJust
42cons mx xs = maybe xs (\x -> x :: xs) mx
44{-| Filters out Nothings and extracts the remaining values.
45-}
46justs : [Maybe a] -> [a]
47justs = foldr cons []