Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir equivalent of C#, Java, C++ enum

Tags:

elixir

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.

like image 620
Christopher Davies Avatar asked Jan 24 '14 23:01

Christopher Davies


1 Answers

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
like image 191
unblevable Avatar answered Sep 21 '22 20:09

unblevable