Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate over union type in Elm?

Tags:

iteration

elm

I have a type union of colors that I want to render to the user. Is it possible to iterate over all type union values?

type Color = Red | Blue | Green | Black

colorToStirng color = 
    case color of
        Red -> "red"
        Blue -> "blue"
        Green -> "green"
        Black -> "black"

colorList = 
    ul
        []
        List.map colorListItem Color  -- <- this is the missing puzzle

colorListItem color = 
    li [class "color-" ++ (colorToString color) ] [ text (colorToString color) ]
like image 300
ondrej Avatar asked Jun 30 '16 20:06

ondrej


1 Answers

The problem with declaring a function like:

type Foo 
  = Bar 
  | Baz

enumFoo = 
  [ Bar 
  , Baz ]

is that you will probably forget to add new enums to it. To solve this, I've been playing with this (hacky, but less hacky than the idea above) idea:

enumFoo : List Foo
enumFoo =
  let
    ignored thing =
      case thing of
          Bar ->  ()
          Baz -> ()
          -- add new instances to the list below!
  in [ Bar, Baz ]

This way you at least get an error for the function and hopefully don't forget to add it to the list.

like image 128
Greg Edwards Avatar answered Sep 20 '22 11:09

Greg Edwards