cs326:daily3

Record your results from Part 1 and the results of running tests from Part 2 on paper and turn in at the beginning of the next class. You can turn in a printout of the code for Part 2, or just email it.

**Part 1.** The following pattern matches use basic collection types. Make a table with two columns: in the first column **guess** if the match succeeds or fails, and what the value of each variable will be if it succeeds. In the second column, show the actual result and bindings you get when you run these in **iex**.

`a = 1`

`{c, d} = {2, 3}`

`{x, :abc} = {123, :abc}`

`{x, y} = {333, :abc, “cat”}`

`{x, y, z} = { {:abc, 123}, 42, {:abc, 123} }`

`{x, y, x} = { {:abc, 123}, 42, {:abc, 123} }`

`{x, y, x} = { {:abc, 123}, 42, true }`

`“Elixir ” <> rest = “Elixir Rocks!”`

`[e, f, g] = [4, :five, [6, 7]]`

`[head | tail] = [4, :five, [6, 7]]`

`[head | tail] = “cat”`

`[a, b, c | tail] = [1, 2, 3, 4, 5, 6]`

**Note**: if you copy/paste these, the double-quote character won't copy correctly, giving unexpected errors. Type the double-quote directly from the keyboard.

**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 0`put_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 x^{2} + 3x + 2. Likewise, we can use a tuple to represent a cubic equation, like `{:cubic, 1, 3, 2, 16}`

for x^{3} + 3x^{2} + 2x + 16.

- In a module
`Daily3`

, write a function`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 (assume the tuples are the correct length and contains numbers). - Name the file containing the module
**daily3.exs**along with code to exercise the function and print the results when run using the**elixir**command.

cs326/daily3.txt · Last modified: 2021/09/06 18:47 by scarl