ch7ex14/

directory
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2022 License: GPL-3.0

README

:chapter: 7
:exercise: 14
:url-base: https://github.com/fenegroni/TGPL-exercise-solutions
:url-workflow: {url-base}/workflows/Exercise {chapter}.{exercise}
:url-action: {url-base}/actions/workflows/ch{chapter}ex{exercise}.yml
:img-badge: image:{url-workflow}/badge.svg?branch=main[link={url-action}]

= Exercise {chapter}.{exercise}

{img-badge}

Define a new concrete type that satisfies the `Expr` interface and provides a new
operation such as computing the minimum value of its operands. Since the `Parse` function
does not create instances of this new type, to use it you will need to construct a syntax tree
directly (or extend the parser).

== Test the new operation, `min`
If I stick to the letter of the exercise,
I can implement a simple test to validate the new operation,
first by creating a syntax tree and then by extending the parser.

The new operation, `min`, is like a function call with two parameters,
e.g. `min(2,3) * 2` will evaluate to 4.

To build the syntax tree we need access to the unexported types in `expr`.
Therefore we will create our test inside the `expr` package, in `min_test.go`.

== Extending the parser
In `TestParseMin` we validate that we extended the parser correctly.

The parser recognises the identifier `min` and expects two arguments,
throwing a `panic` if too many or too few arguments are given.

== Some thoughts about the exercise
The operation suggested by the exercise doesn't seem to require a whole new concrete type.
I would rather extend `call` with a `min` function instead.

Looking at the grammar, I struggle to think of an operation that would require a new concrete type.

----
expr = num                         a literal number, e.g., 3.14159
     | id                          a variable name, e.g., x
     | id '(' expr ',' ... ')'     a function call
     | '-' expr                    a unary operator (+-)
     | expr '+' expr               a binary operator (+-*/)
----

The concrete types implementing `Expr` seem to be at the very first level of the grammar.
A ternary operator is the only operation I can think of to require a new concrete type.
Any other operation would be an extension to the original set.

Perhaps this exercise should be about making the existing concrete types extendable.
This would be better implemented using reflection and injection.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL