Enums, several different ways

With reference to the discussion we had here:

How to do enums in Elm

I decided to have a go at creating an enums package for this. There is already one here:


One thing I found odd about that one was the signature for decoder:

decodeEnumValue : Enum a -> String -> Decoder a

Surely it should be:

decodeEnumValue : Enum a -> Decoder a

So the revised API I came up with is here, along with some examples of how to use it:


I left out the functions for creating HTML option or select, since those seem not to be a core concern of the data model.

Any thoughts?

1 Like

Also my package :wink:

type Fruit
    = Apple
    | Banana
    | Mango

fruit : Enum Fruit
fruit =
        [ ( "Apple", Apple )
        , ( "Banana", Banana )
        , ( "Mango", Mango )
type alias Enum a =
    { toString : a -> String
    , fromString : String -> Maybe a
    , encode : a -> Value
    , decoder : Decoder a
    , list : List ( String, a )

Yes, saw that one too. Didn’t seem to be based on the “How to do enums in Elm” discussion though - but not completely dissimilar.

I think I could get Enum a -> a -> Int for free by having the make function enumerate the list of values, so would not need a separate model for EnumInt.

I think that requiring the pattern matcher (rather than listing) is better for the user, as it helps not forgetting stuff.
I’ve written about it in relation to elm-codec

What do you mean by ‘requiring the pattern matcher’? Can you give a little example in code, I don’t quite follow you.

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