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 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.int
|> 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
_ -> Json.Decode.fail ("Unknown mode: " ++ String.fromInt modeInt)
)