|
|
|
|
|
by searchableguy
2168 days ago
|
|
This article is good (although they could work on examples a bit more). One thing I have really found useful when working with elixir is that it gives you a way to abstract common patterns or add more use cases by differentiating based on arity and pattern matching. it's easy to write the average function in the article in this way. def average(arg) when Enum.all(arg, &is_string/1) do
# implementation
end
def average(arg) when Enum.all(arg, &is_integer/1) # for the int
which would be a more proper abstraction as it hides details of the type of your data.or using pattern matching in the arguments. def shape("circle", ...) do
# implementation
end
def shape("square", ...) do
# different implementation
end
When you have map as an argument, you can do def is_good(%{ hn: HN }) do
IO.puts "#{HN.someprop} is good"
end
def is_good(%{reddit: Reddit}) do
IO.puts "#{Reddit.someprop} is bad"
end
def multiply_on_two_numbers_otherwise_square(a), do: a * a
def multiply_on_two_numbers_otherwise_square(a, b), do: a * b
My examples are trivial but this really gives you some awesome refactoring powers. |
|