문제

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.

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top