在 elm 中对 case 表达式进行分组 (0.18)

Grouping case expressions in elm (0.18)

在 elm (0.18) 中有没有办法将一系列做同样事情的 case 表达式组合在一起?

例如:

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"

否,但您可以按如下方式重构您的类型:

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
    ...