This module is for creating more advanced pattern matches in your case expressions.
The general usage looks something like this
import Elm.Case as Case
import Elm.Case.Branch as Branch
example =
Case.custom myValue
(Elm.Annotation.named [] "Msg")
-- Define all the branches in your case
[ Branch.variant1 "ButtonClicked" (Branch.var "id") <|
\id -> Elm.Op.append id (Elm.string " was clicked!")
-- A branch which also destructures a record
, Branch.variant1 "FormSubmitted" (Branch.record2 Tuple.pair "id" "isValid") <|
\( id, isValid ) ->
Elm.ifThen isValue
(Elm.string "Form is valid")
(Elm.string "Form is NOT valid")
]Which generates
case myValue of
ButtonClicked id ->
"Button " ++ id ++ " was clicked!"
FormSubmitted { id, isValid } ->
if isValid then
"Form is valid"
else
"Form is NOT valid"This is the most basic kind of pattern - it matches anything and gives it a variable name.
import Elm.Case.Branch as Branch
Branch.variant1 "Username" (Branch.var "username") <|
\username ->
Elm.Op.append
(Elm.string "Hello ")
usernameResults in
Username username ->
"Hello " ++ usernamePattern match with a literal Int.
import Elm.Case.Branch as Branch
Branch.just (Branch.int 2 (Elm.int 5))Results in
Just 2 ->
5Matches a literal String.
example =
Branch.just (Branch.string "admin")
|> Branch.map
(\str ->
Elm.string "This user is an admin!"
)Results in
case user.kind of
Just "admin" ->
"This user is an admin!"Matches a literal Char.
Branch.tuple (Branch.var "one") (Branch.var "two")
|> Branch.map
(\( one, two ) ->
Elm.Op.append one two
)Match on a list of items
[ "first", "second" ] ->
"firstsecond"Could be represented like
Branch.list
{ patterns =
[ Branch.string "first"
, Branch.string "second"
]
, gather = \item gathered -> item :: gathered
, startWith = []
, finally = Elm.string
}Pattern match on an open list where you can have access to remaining "tail" of items.
So, something like this:
"first" :: "second" :: remaining ->
remainingCould be represented like
Branch.listWithRemaining
{ patterns =
[ Branch.string "first"
, Branch.string "second"
]
, remaining = Branch.var "remaining"
, gather = \item gathered -> item :: gathered
, startWith = []
, finally =
\gathered remaining ->
remaining
}The Err value of a result.
The Ok value for a Result
This will help destructure record fields if you know what fields you want.
Here's an example using an intermediate record to help us out!
{-| We define a record to help us out!
-}
type alias Details =
{ id : Elm.Expression
, name : Elm.Expression
}
Case.custom (Elm.val "msg") (Type.named [] "Msg")
[ Branch.variant1 "ButtonClicked" (Branch.record2 Details "id" "name") <|
\{ id, name } ->
Elm.tuple id name
]Which generates
case msg of
ButtonClicked { id, name } ->
( id, name )An empty record pattern!
These helpers let you define a Custom Type pattern with a builder.
as)