Elixir相当于C#,Java,C++枚举

Chr*_*ies 6 elixir

在C#中,我可能会声明一个这样的枚举:

enum QuestionType { Range, Text };
Run Code Online (Sandbox Code Playgroud)

我如何在Elixir中这样做?我想做的是能够模式匹配这样的东西:

def VerifyAnswer(QuestionType.range, answer) do
  assert answer >= 0 && answer <= 5
end
Run Code Online (Sandbox Code Playgroud)

或类似的东西,其中QuestionType.range是一个数字常量,因此它可以有效地存储在DB中或序列化为int到JSON.

unb*_*ble 9

您可以使用其他语言中使用枚举的原子.例如,您可以:

# 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" }
Run Code Online (Sandbox Code Playgroud)

你可以在这里使用模式匹配:

def verify_answer(question = { :question, range, text }, answer) do
  assert answer in range
end
Run Code Online (Sandbox Code Playgroud)