Skip to content

Instantly share code, notes, and snippets.

@rupertlssmith
Last active October 30, 2019 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rupertlssmith/2d24347a94efc68d1276d62363d00bbe to your computer and use it in GitHub Desktop.
Save rupertlssmith/2d24347a94efc68d1276d62363d00bbe to your computer and use it in GitHub Desktop.
Elm Enums
-- This way gives you a custom type, which can be used to branch on in code with case of.
type Pet
= Cat
| Dog
| Snake
| Spider
petEnum =
Enum.make
[ Cat
, Dog
, Snake
, Spider
]
(\pet ->
case pet of
Cat ->
"Cat"
Doc ->
"Dog"
Snake ->
"Snake"
Spider ->
"Spider"
)
-- The Pet type could be made opaque so that outside of its defining module, new values cannot be added to the enum
-- The toString function is easy to write.
-- This enum is easy to modify, requiring only that a new item be added to the list.
type Pet
= Pet String
petEnum =
Enum.make
[ Pet "Cat"
, Pet "Dog"
, Pet "Snake"
, Pet "Spider"
]
(\Pet kind -> kind)
-- This enum is just a string, so provides no guarantees that an instance of it really is in the enum.
-- The toString function is easy to write.
-- This enum is easy to modify, requiring only that a new item be added to the list.
petEnum =
Enum.make
[ "Cat"
, "Dog"
, "Snake"
, "Spider"
]
identity
module Enum exposing (Enum, decoder, encoder, find, make)
type Enum a
= Enum (List a) (a -> String)
make : List a -> (a -> String) -> Enum a
toString : Enum a -> a -> String
find : Enum a -> String -> Maybe a
decoder : Enum a -> Decoder a
encoder : Enum a -> a -> Value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment