Purpose: using named functions in a module.
NOTE!!! We probably don't need the Part 3 problem anymore…does it offer anything new???
Reading: the first three sections in Elixir School:Named Functions and Sections 6.1-6.3 of the Thomas text.
Create a file maths.exs
while defines a module Maths
. Define the functions below in this module, along with code to exercise the functions (and print the results) using the tests as shown. For the second and third function, add two tests of your own (along with expected results). This script should run properly using the elixir program which is how I'll test them.
While you are developing your solutions, you can try things out in iex; the first section of Ch. 6 describes ways to compile while using iex.
Part 1.
Daily2.average(10, 10)
Daily2.average(5, 7)
Daily2.average(5, 8)
Daily2.average(5.0, 8.0)
Daily2.average(12.4, 13.7)
discrim(a, b, c)
which returns b2 - 4ac; for example, Daily2.discrim(2, 7, 5)
should return 9.0discrim
function to define quad_roots(a, b, c)
that returns the two roots of a quadratic function, should they exist, as a tuple. Note that Elixir does not define a square root function, since it is already available in the Erlang libraries. To call this function, use :math.sqrt
. Daily2.quad-roots(2, 7, 5)
would return {-1.0 -2.5}
def return_tuple() do x = 1 y = 2 {x, y} end
Part 2. You saw the tuple data type in Daily 1. There are two built-in functions for accessing tuple elements and creating new tuples from existing ones:
elem(tp, index)
returns the nth value in the tuple tp
, starting at 0put_elem(tp, n, value)
returns a new tuple replacing the nth element of tp
with value
We can represent a quadratic equation as a tuple where each element is a coefficient; for example we can use {:quad, 1, 3, 2}
to represent x2 + 3x + 2. Likewise, we can use a tuple to represent a cubic equation, like {:cubic, 1, 3, 2, 16}
for x3 + 3x2 + 2x + 16.
Daily4.Quadratic
in a script file daily4.exs
.eval_equation
that takes a tuple and a value for x
and returns the result of evaluating the equation at that value. Use pattern matching and multiple clauses to determine which type of equation you have, quadratic or cubic (you can assume tuples are the correct length and contain numbers in the right places).
Part 3. In module Daily4.Quadratic
containing these functions:
degenerate
- takes a number, the first coefficientquad_solutions
- takes a tuple containing three numbers, the coefficientsdiscriminant
- this you already have