DEV Community

Discussion on: My First Week With Elixir As A Rubyist

Collapse
 
edisonywh profile image
Edison Yap

Great writeup! I've also started learning Elixir not long ago and have been loving every minute of it.

Just a slight suggestion, you can add guards into your function headers too, so your recursion example could even be refactored to something like: (btw, you missed out a do in your defmodule)

defmodule Example do
  def any?([], _a), do: false
  def any?([head | _tail], a) when head == a, do: true
  def any?([_head | tail], a), do: any?(tail, a)
end

This uses what we call guard clause, which is the when head == a part of the code.

Basically, most of the time if you see an if statement concerning the arguments passed into the function, you probably could do away with if/else and pattern match on the function head to do the same thing :)

Collapse
 
fidr profile image
Robin

You can also match on equality by re-using the same param name in the function definition:

defmodule Example do
  def any?([], _a), do: false
  def any?([a | _tail], a), do: true
  def any?([_head | tail], a), do: any?(tail, a)
end
Collapse
 
ssolo112 profile image
Steven Solomon

I really dig the pattern for head being equal to the element you are looking for.

Collapse
 
ssolo112 profile image
Steven Solomon • Edited

Thank you for the tip about guard clauses, I definitely love getting rid of conditions =)