Last active
October 30, 2019 16:20
-
-
Save rupertlssmith/2d24347a94efc68d1276d62363d00bbe to your computer and use it in GitHub Desktop.
Elm Enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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" | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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