on 4bec310 help sign in
elk/libraries/Maybe.elm
65 lines 1.6 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{-| Provide a default value and a function to extract the contents of a `Maybe`.
25When given `Nothing` you get the default, when given a `Just` you apply the
26function to the associated value.
28 isPositive : Maybe Int -> Bool
29 isPositive maybeInt = maybe False (\n -> n > 0) maybeInt
31 map : (a -> b) -> Maybe a -> Maybe b
32 map f m = maybe Nothing (\x -> Just (f x)) m
33-}
34maybe : b -> (a -> b) -> Maybe a -> b
35maybe b f m = case m of
36 Just v -> f v
37 Nothing -> b
39{-| Check if a maybe happens to be a `Just`.
41 isJust (Just 42) == True
42 isJust (Just []) == True
43 isJust Nothing == False
44-}
45isJust : Maybe a -> Bool
46isJust = maybe False (\_ -> True)
48{-| Check if constructed with `Nothing`.
50 isNothing (Just 42) == False
51 isNothing (Just []) == False
52 isNothing Nothing == True
53-}
54isNothing : Maybe a -> Bool
55isNothing = not . isJust
57cons : Maybe a -> [a] -> [a]
58cons mx xs = maybe xs (\x -> x :: xs) mx
60{-| Filters out Nothings and extracts the remaining values.
62 justs [Just 0, Nothing, Just 5, Just 7] == [0,5,7]
63-}
64justs : [Maybe a] -> [a]
65justs = foldr cons []