Search code examples
iterationelm

Is it possible to iterate over union type in 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) ]

Solution

  • Unfortunately, no. It is not possible.

    For a simple type with a finite number of values like your Color type it might seem like the compiler should be able to generate such a list. As far as the complier is concerned though, there is no difference between your type and a type like

    type Thing = Thing String
    

    To iterate over all the values of type Thing would then require iterating over all the values of type String.