Best way to represent an enum

I have a REST API that returns a json document, one field is numeric, mode. The values of the mode field are limited 0-3, they represent different states. To me this looks like an enum from other languages. What is the recommend way to represent this data in enum? I was thinking a Union type would be best, but then I was thinking about how to decode that and thought maybe there is a better way.

This is what I was thinking of doing.

type Mode
  = OFF
  | HEAT
  | COOL
  | AUTO
1 Like

This is a great way to model this. For decoding you would map each number to the value that matches, and fail when an unexpected value is reached. Possibly something like

import Json.Decode

type Mode
    = Off
    | Heat
    | Cool
    | Auto

decode : Json.Decode.Decoder Mode
decode =
        |> Json.Decode.andThen
            (\modeInt ->
                case modeInt of
                        0 -> Json.Decode.succeed Off
                        1 -> Json.Decode.succeed Heat
                        2 -> Json.Decode.succeed Cool
                        3 -> Json.Decode.succeed Auto
                        _ -> ("Unknown mode: " ++ String.fromInt modeInt)

Thank you that is exactly what I wound up doing.

1 Like

Some different ways of doing Enums in Elm were discussed here:

If you end up dealing with a lot of Enums, this package I wrote might be helpful as well, reduces the boilerplate a bit: enum 1.0.1


This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.