Math With Protocols
Mix.install([
{:jason, "~> 1.4"},
{:kino, "~> 0.9", override: true},
{:youtube, github: "brooklinjazz/youtube"},
{:hidden_cell, github: "brooklinjazz/hidden_cell"}
])
Navigation
Home Report An Issue ProtocolsBattle MapMath With Protocols
You’re going to create a Math
module that uses protocols to add or subtract integers, strings, and lists with the same add/2
and subtract/2
functions.
2 = Math.add(1, 1)
[1, 2, 3, 4] = Math.add([1, 2], [3, 4])
"hello there" = Math.add("hello there")
1 = Math.subtract(2, 1)
[2, 3] = Math.subtract([3, 2, 3], [3])
"ab" = Math.subtract("babc", "bc")
Raise a ProtocolUndefined
error if an invalid value is provided.
Math.add(%{}, %{})
** (Protocol.UndefinedError) protocol Math not implemented for %{} of type Map
Hint: Subtracting Strings
Consider converting your strings to a list, then subtract the two lists together then join your result back into a string.
Example Solution
defprotocol Math do
def add(value1, value2)
def subtract(value1, value2)
end
defimpl Math, for: Integer do
def add(integer1, integer2) do
integer1 + integer2
end
def subtract(integer1, integer2) do
integer1 - integer2
end
end
defimpl Math, for: BitString do
def add(string1, string2) do
string1 <> string2
end
def subtract(string1, string2) do
(String.split(string1, "") -- String.split(string2, ""))
|> Enum.join()
end
end
defimpl Math, for: List do
def add(list1, list2) do
list1 ++ list2
end
def subtract(list1, list2) do
list1 -- list2
end
end
Define implementations for the Math
protocol as documented below.
defprotocol Math do
@moduledoc """
iex> Math.add(1, 1)
2
iex> Math.add([1, 2], [3, 4])
[1, 2, 3, 4]
iex> Math.add("hello ", "there")
"hello there"
iex> Math.subtract(2, 1)
1
iex> Math.subtract([3, 2, 3], [3])
[2, 3]
iex> Math.subtract("babc", "bc")
"ab"
iex> Math.add({}, {})
** (Protocol.UndefinedError) protocol Math not implemented for {} of type Tuple
"""
def add(value1, value2)
def subtract(value1, value2)
end
# Define Implementations...
Commit Your Progress
DockYard Academy now recommends you use the latest Release rather than forking or cloning our repository.
Run git status
to ensure there are no undesirable changes.
Then run the following in your command line from the curriculum
folder to commit your progress.
$ git add .
$ git commit -m "finish Math With Protocols exercise"
$ git push
We’re proud to offer our open-source curriculum free of charge for anyone to learn from at their own pace.
We also offer a paid course where you can learn from an instructor alongside a cohort of your peers. We will accept applications for the June-August 2023 cohort soon.