在榆树列表上的模式匹配

时间:2017-09-07 21:40:18

标签: haskell pattern-matching 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中完成吗?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

是!

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