用榆树分组案例表达式(0.18)

时间:2017-09-17 04:59:34

标签: elm case-statement

榆树(0.18)中是否有一种方法可以将一系列表达同一事物的案例表达式组合在一起?

例如:

type Character
    = Sleepy
    | Happy
    | Grumpy
    | Dopey
    | Sneezy
    | Bashful
    | Doc
    | SnowWhite
    | Queen


getKindOfCharacter : Character -> String
getKindOfCharacter character =
  case character of
    (Sleepy | Happy | Grumpy | Dopey | Sneezy | Bashful | Doc) ->
      "Dwarf"
    SnowWhite ->
      "Hero"
    Queen ->
      "Villain"

1 个答案:

答案 0 :(得分:4)

不,但你可以按如下方式重构你的类型:

type Character
    = Dwaft Dwarf
    | SnowWhite
    | Queen

type Dwarf
    = Sleepy
    | Happy
    | Grumpy
    | Dopey
    | Sneezy
    | Bashful
    | Doc

getKindOfCharacter : Character -> String
getKindOfCharacter character =
  case character of
    Dwarf _ ->
      "Dwarf"
    SnowWhite ->
      "Hero"
    Queen ->
      "Villain"

甚至更好......

type Character
    = Dwaft Dwarf
    | Hero Hero
    | Villain Villain

type Dwarf
    = Sleepy
    | Happy
    | Grumpy
    | Dopey
    | Sneezy
    | Bashful
    | Doc

type Hero
    = SnowWhite

type Villain
    = Queen

然后你不需要getKindOfCharacter函数,因为Character类型会提供相同的信息。

let 
    hero : Character
    hero = Hero SnowWhite

    villain : Character
    villain = Villain Queen

    dwarf : Character
    dwarf = Dwarf Dopey
in
    ...