【问题标题】:Elixir equivalent of C#, Java, C++ enumElixir 等效于 C#、Java、C++ 枚举
【发布时间】:2016-07-04 13:33:37
【问题描述】:

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

enum QuestionType { Range, Text };

我将如何在 Elixir 中执行此操作?我想做的是能够像这样进行模式匹配:

def VerifyAnswer(QuestionType.range, answer) do
  assert answer >= 0 && answer <= 5
end

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

【问题讨论】:

  • 你在freenode上试过#elixir-lang吗?甚至 Jose Valim 也可能会回答那里提出的问题。虽然很高兴在 SO 上看到更多 Elixir 问题。
  • 其实在 SO 中提问是非常好的,因为它可以帮助将来的其他人。 :) 我也经常在这里查看!

标签: elixir


【解决方案1】:

您可以在其他语言中使用枚举的地方使用原子。例如,您可以:

# 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" }

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

def verify_answer(question = { :question, range, text }, answer) do
  assert answer in range
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2021-01-24
    • 2014-01-17
    • 1970-01-01
    • 2014-04-15
    • 2011-06-03
    • 2010-11-30
    相关资源
    最近更新 更多