Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Created September 1, 2014 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arialdomartini/a4193422d377a719d2d6 to your computer and use it in GitHub Desktop.
Save arialdomartini/a4193422d377a719d2d6 to your computer and use it in GitHub Desktop.
Étude 3-1: Pattern Matching in Elixir and Erlang
### Elixir
defmodule Geom do
def area(:rectangle, length, width) do
length * width
end
def area(:triangle, base, height) do
base * height / 2
end
def area(:ellipse, a, b) do
a * b * :math.pi
end
end
### Erlang
-module(geom).
-export([area/3]).
area(rectangle, Length, Width) -> Length * Width;
area(ellipse, A, B) -> math:pi() * A * B;
area(triangle, Base, Height) -> Base * Height / 2.
@emadb
Copy link

emadb commented Sep 1, 2014

You can rewrite the code like this:

### Elixir    
defmodule Geom do
  def area(:rectangle, length, width) do: length * width
  def area(:triangle, base, height) do: base * height / 2
  def area(:ellipse, a, b) do: a * b * :math.pi 
end

@arialdomartini
Copy link
Author

It seems that the final end is mandatory, thou :(

defmodule Geom do
  def area(:rectangle, length, width) do: length * width end
  def area(:triangle, base, height) do: base * height / 2 end
  def area(:ellipse, a, b) do: a * b * :math.pi end
end

@emadb
Copy link

emadb commented Sep 1, 2014

It's not necessary, but I missed a comma:

defmodule Geom do
  def area(:rectangle, length, width), do: length * width 
  def area(:triangle, base, height), do: base * height / 2
  def area(:ellipse, a, b), do: a * b * :math.pi
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment