Reputation: 2674
Can you pattern match on a list of items in Elm 0.18? For example:
type Thing = Foo | Bar | Baz
things : List Thing
things : [ Foo, Bar, Baz ]
caseStatement : Thing -> Bool
caseStatement thing =
case thing of
expressionSayingThatItIsInThingsList ->
True
_ ->
False
Also, can this be done in Haskell?
Upvotes: 1
Views: 1084
Reputation: 24399
Yes!
case thing of
Foo :: Foo :: Bar :: [] ->
"two foos and a bar"
Bar :: stuff ->
"a bar and then " ++ (toString stuff)
_ ->
"something else"
Upvotes: 1
Reputation: 42698
Elm is based on Haskell, actually has lot of less features, you can pattern match your type easily element by element or check if it is in the list:
data Thing = Foo | Bar | Baz deriving (Eq, Show)
things :: [Thing]
things = [ Foo, Bar, Baz ]
caseStatement :: Thing -> Bool
caseStatement thing = thing `elem` things
Pattern matching:
caseStatement :: Thing -> Bool
caseStatement Foo = True
caseStatement Bar = True
caseStatement Baz = True
caseStatement _ = False
Here you have a live example
In Elm you can use List.member
import List
type Thing = Foo | Bar | Baz
things : List Thing
things = [ Foo, Bar, Baz ]
caseStatement : Thing -> Bool
caseStatement thing = List.member thing things
Pattern matching it:
caseStatement : Thing -> Bool
caseStatement thing = case thing of
Foo -> True
Bar -> True
Baz -> True
_ -> False
Upvotes: 4