Elixir - Case Statement


Advertisements

Case statement can be considered as a replacement for the switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, Elixir executes the code associated with that case and exits the case statement. If no match is found, it exits the statement with an CaseClauseError that displays no matching clauses were found. You should always have a case with _ which matches all values. This helps in prevention of the above mentioned error. Also this is comparable to the default case in switch-case statements.

Syntax

The syntax of an if statement is as follows −

case value do
      matcher_1 -> #code to execute if value matches matcher_1
	matcher_2 -> #code to execute if value matches matcher_2
	matcher_3 -> #code to execute if value matches matcher_3
	...
	_ -> #code to execute if value does not match any of the above
end

Example

case 3 do
   1 -> IO.puts("Hi, I'm one")
   2 -> IO.puts("Hi, I'm two")
   3 -> IO.puts("Hi, I'm three")
   _ -> IO.puts("Oops, you dont match!")
end

The above program generates the following result.

Hi, I'm three

Note that the case selection is done using pattern matching, so you can use the standard pattern matching techniques.

elixir_decision_making.htm
Advertisements