2

Is there a way in elm (0.18) to group together a series of case expressions that do the same thing?

For example:

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"
Mark Karavan
  • 2,654
  • 1
  • 18
  • 38

1 Answers1

5

No, but you can refactor your types as follows:

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"

Or even better...

type Character
    = Dwaft Dwarf
    | Hero Hero
    | Villain Villain

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

type Hero
    = SnowWhite

type Villain
    = Queen

Then you woudn't need the getKindOfCharacter function because the Character type would provide the same info.

let 
    hero : Character
    hero = Hero SnowWhite

    villain : Character
    villain = Villain Queen

    dwarf : Character
    dwarf = Dwarf Dopey
in
    ...
Emmanuel Rosa
  • 9,697
  • 2
  • 14
  • 20