Elixir case do pattern matching example


case do allow us to quickly specify some condition and then we're good to go. The only catch here is the sequence condition (1st condition) a <=3 and (2nd condition) a > 3 must be in sequence, otherwise elixir will complaint. It is not a bug, just a logic error that you might want to avoid

COND DO

defmodule Test do  def say(a) do
    cond do
      a <= 3 -> "lesser than3 "
      a > 3  -> "bigger than 3"
   end
  end
end



CASE DO

Notice how we specify condition for bigger than 2 conditions.


defmodule Test do
  def say(a) do
    case a do
     1 -> "1"
     2 -> "2"
     n when n > 2 -> "Big"
    end
  end
end



Creating exceptions using defexception. 

Yes it is why it is called defexceptions. Considered it a special keyword to do this specifically.

Example code and usage :-

defmodule AppError do
   defexception message: "app error"
   end
end

// invoke it 
raise defexception 



Raising error and handling it

You can raise and handle exception using the following construct. Please note "e in RuntimeError"or whatever error is required although you decided to do something else.

try do
 raise "error ...."
rescue
   e in RuntimeError -> IO.puts "error"
end



Passing into function as parameter 

You can pass in function as parameter using the following code :-

Test.run(&Test.say/0)

Please note that parameter "say/0" is passed in.

And the module is given here. 

defmodule Test do
   def sum(a, b), do: a + b
   def run(funct), do: funct.()
   def say() do
     IO.puts "hello"
   end
end








Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm