genthaler / elm-enum / Enum

Enum is an implementation of OO style Enums in Elm.

The implementation was guided initially by this Discourse discussion, then by usage in my personal projects.

Basic Enum helpers


type Enum a

Union type representing an Enum. Note that this an opaque type; use makeEnum to construct Enums.

makeEnum : List a -> (a -> String) -> Enum a

Enum constructor.

type DataType
    = Text
    | Date
    | Email
    | Address
    | Postcode
    | State
    | Gender


dataTypeEnum : Enum DataType
dataTypeEnum =
    Enum.makeEnum
        [ Text
        , Date
        , Email
        , Address
        , Postcode
        , State
        , Gender
        ]
        Basics.toString

toString : Enum a -> a -> String

Return the string representation of the Enum.

type DataType
    = Text

enum = makeEnum [Text] Basics.toString

(Enum.toString enum Text) == "Text"

findEnumValue : Enum a -> String -> Result String a

If possible, return the union type tag from the String representation.

type DataType
    = Text

enum = makeEnum [Text] Basics.toString

(Enum.findEnumValue enum "Text") == Ok Text
(Enum.findEnumValue enum "Foo") == Err "Foo"

JSON-related helpers

decodeEnumValue : Enum a -> String -> Json.Decode.Decoder a

Converts the output of findEnumValue to a Json.Decode.Decoder

HTML-related helpers

onEnumInput : Enum a -> (a -> msg) -> Html.Attribute msg

Creates an input handler for the Enum.

enumSelect : Enum a -> (a -> msg) -> a -> Html msg

Takes an Enum, a Msg that tags the Enum's underlying union type, and a currently selected value, and constructs a <select> element.

view model =
    div [] [ Enum.enumSelect Model.dataTypeEnum SetDataType model.dataType, text model.message ]

Take a look at the example project for a simple use-case.