on 727d708 help sign in
elk/libraries/Maybe.elm
34 lines 904 B history raw
2module Maybe where
4import open Basics
5import open List
7-- The Maybe datatype. Useful when a computation may or may not
8-- result in a value (e.g. logarithm is defined only for positive numbers).
9data Maybe a = Just a | Nothing
11-- Apply a function to the contents of a `Maybe`.
12-- Return default when given `Nothing`.
13maybe : b -> (a -> b) -> Maybe a -> b
14maybe b f m = case m of
15 Just v -> f v
16 Nothing -> b
18-- Check if constructed with `Just`.
19isJust : Maybe a -> Bool
20isJust = maybe False (\_ -> True)
22-- Check if constructed with `Nothing`.
23isNothing : Maybe a -> Bool
24isNothing = not . isJust
27-- If `Just`, adds the value to the front of the list.
28-- If `Nothing`, list is unchanged.
29cons : Maybe a -> [a] -> [a]
30cons mx xs = maybe xs (\x -> x :: xs) mx
32-- Filters out Nothings and extracts the remaining values.
33justs : [Maybe a] -> [a]
34justs = foldr cons []