Reputation: 4551
In C#, I might declare an enumeration like this:
enum QuestionType { Range, Text };
How would I do this in Elixir? What I would like to do is be able to pattern-match something like this:
def VerifyAnswer(QuestionType.range, answer) do
assert answer >= 0 && answer <= 5
end
Or something like this, where QuestionType.range
is a numeric constant, so it can be efficiently stored in DBs or serialized as an int to JSON.
Upvotes: 7
Views: 2081
Reputation: 1316
You can use atoms where enums are used in other languages. For example, you could:
# use an atom-value tuple to mark the value '0..5' as a range
{ :range, 0..5 }
# group atoms together to represent a more involved enum
question = { :question, { :range, 0..5 }, { :text, "blah" } }
# use the position of an element to implicitly determine its type.
question = { :question, 0..5, "blah" }
You can use pattern matching here like so:
def verify_answer(question = { :question, range, text }, answer) do
assert answer in range
end
Upvotes: 9