Elm 列表中的模式匹配

Pattern Matching on a List in Elm

你能在 Elm 0.18 中对项目列表进行模式匹配吗?例如:

type Thing = Foo | Bar | Baz

things : List Thing
things : [ Foo, Bar, Baz ]

caseStatement : Thing -> Bool
caseStatement thing =
  case thing of
    expressionSayingThatItIsInThingsList ->
      True
    _ ->
      False

此外,这可以在 Haskell 中完成吗?

Elm 基于 Haskell,实际上有很多较少的功能,您可以轻松地逐个元素地模式匹配您的类型或检查它是否在列表中:

data Thing = Foo | Bar | Baz deriving (Eq, Show)

things :: [Thing]
things = [ Foo, Bar, Baz ]

caseStatement :: Thing -> Bool
caseStatement thing = thing `elem` things

模式匹配:

caseStatement :: Thing -> Bool
caseStatement Foo = True
caseStatement Bar = True
caseStatement Baz = True
caseStatement _   = False

这里有一个live example

在 Elm 中你可以使用 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

匹配的模式:

caseStatement : Thing -> Bool
caseStatement thing = case thing of
    Foo -> True
    Bar -> True
    Baz -> True
    _   -> False

是的!

case thing of
   Foo :: Foo :: Bar :: [] ->
      "two foos and a bar"
   Bar :: stuff ->
      "a bar and then " ++ (toString stuff)
    _ ->
      "something else"