forked from orion/obsidian
2.2 KiB
2.2 KiB
Pattern matching
case <expr> of
<arm>+
where arm
is:
<pattern> -> <expr>
pattern
can be:
- Data Structures/data constructors
- Records literals, containing patterns
- integer & number literals
- string literals
- array literals, containing patterns
- wildcard
_
Guard Clauses
Case arms can have Functions/Defining/Guard Clause like Functions definitions:
case _ of
"" -> Nothing
s | String.Util.startsWith "/" -> Just s
| otherwise -> Nothing
Examples
Match on Int
when zero
nonzeroInt :: Int -> Maybe Int
nonzeroInt n =
case n of
0 -> Nothing
n' -> Just n'
Match on Arity Data Structures/data constructors:
data Letter = A | B | C
letterToString :: Letter -> String
letterToString l =
case l of
A -> "a"
B -> "b"
C -> "c"
Match on Arity Data Structures/data constructors:
isJust :: forall a. Maybe a -> Boolean
isJust m =
case m of
Just a -> true
Nothing -> false
Match on Arity Data Structures/data constructors:
data ComplexDataType = Complex Int Int String String
complex :: ComplexDataType -> String
complex m =
case m of
Complex a b c d -> (show a) <> (show b) <> c <> d
Match on a record field that is Maybe
, continuing if the field is Just
unMaybeFirstName :: {firstName :: Maybe String} -> Maybe {firstName :: String}
unMaybeFirstName r =
case r of
{firstName: Just fn} -> Just {firstName: fn}
_ -> Nothing
Match on an array of a
into Either:
zeroOneOrMore ::
forall a
. Array a
-> Either (Maybe a) (Array a)
zeroOneOrMore a =
case a of
[] -> Left Nothing
[a] -> Left (Just a)
_ -> Right a
Deserialize strings literals into a Data Structures/data
data Animal = Dog | Cat | Giraffe
animalFromString :: String -> Maybe Animal
animalFromString s =
case s of
"dog" -> Just Dog
"cat" -> Just Cat
"giraffe" -> Just Giraffe
_ -> Nothing