Question

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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top