Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Math

math.livemd

Math

Mix.install([
  {:kino, github: "livebook-dev/kino", override: true},
  {:kino_lab, "~> 0.1.0-dev", github: "jonatanklosko/kino_lab"},
  {:vega_lite, "~> 0.1.4"},
  {:kino_vega_lite, "~> 0.1.1"},
  {:benchee, "~> 0.1"},
  {:ecto, "~> 3.7"},
  {:math, "~> 0.7.0"},
  {:faker, "~> 0.17.0"},
  {:utils, path: "#{__DIR__}/../utils"},
  {:tested_cell, git: "https://github.com/BrooklinJazz/tested_cell"}
])

Navigation

Return Home Report An Issue

Math

In this exercise, you’re going to create a Math module that handles adding, subtracting, and multiplying different data types.

You might consider relying on either guards, protocols, or behaviours to accomplish the desired functionality.

The Math module should be able to add/2, subtract/2, and multiply/2 integer, float, string, list, and ranges.

Integers and Floats

Integers and floats should work as expected with the +, *, and - operators.

Math.add(1, 1)
2

Math.add(1, 2.5)
3.5

Math.subtract(3, 1)
2

Math.multiply(5, 5)
25

Lists

Lists should work the same as with the ++ and -- operators. Multiplication should use an integer for the second argument and repeat elements in the list. (You may find the List.duplicate/2 and List.flatten/1 functions to be useful)

Math.add([1,2], [3,4])
[1,2,3,4]

Math.subtract([1,2,3], [2, 3])
[1]

Math.multiply([1,2,3], 3)
[1,2,3, 1,2,3, 1,2,3]

Ranges

Ranges should perform the operation on the start and the end of each list.

Remember that you can pattern match on a range like so:

first..last//step = 1..10
{first, last, step}
first..last//step = 2..20//3
{first, last, step}

You do not need to take the range step into account. i.e. 1..10//2

Math.add(1..10, 2..20)
3..30
Math.subtract(5..20, 2..5)
3..15
Math.multiply(5..20, 1..5)
5..100

Strings

  • add/2 should work the same as the <> operator.
  • subtract/2 should remove the first matching letter from the string.
  • multiply/2 should repeat the second string after every letter in the first string.
Math.add("he", "llo")
"hello"

Math.subtract("here", "he")
"re"

Math.subtract("here", "hee")
"r"

Math.multiply("123", "abc")
"1abc2abc3abc"

Your Solution

Enter your solution below between the comments. Ensure you create a Math module or protocol.

# Enter your answer below

# Enter your answer above
Utils.feedback(:math_module, Math)

Commit Your Progress

Run the following in your command line from the project folder to track and save your progress in a Git commit.

$ git add .
$ git commit -m "finish math exercise"