mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-04-17 05:57:19 +02:00
Show expressions trees (#2425)
While giving the class, I noticed that a few people were not used to this kind of recursive structures. A diagram could help here.
This commit is contained in:
parent
8873e3ea53
commit
6e829ff89a
@ -6,6 +6,52 @@ minutes: 30
|
|||||||
|
|
||||||
Let's write a simple recursive evaluator for arithmetic expressions.
|
Let's write a simple recursive evaluator for arithmetic expressions.
|
||||||
|
|
||||||
|
An example of a small arithmetic expression could be `10 + 20`, which evaluates
|
||||||
|
to `30`. We can represent the expression as a tree:
|
||||||
|
|
||||||
|
<!-- mdbook-xgettext: skip -->
|
||||||
|
|
||||||
|
```bob
|
||||||
|
.-------.
|
||||||
|
.------ | + | ------.
|
||||||
|
| '-------' |
|
||||||
|
v v
|
||||||
|
.--------. .--------.
|
||||||
|
| 10 | | 20 |
|
||||||
|
'--------' '--------'
|
||||||
|
```
|
||||||
|
|
||||||
|
A bigger and more complex expression would be `(10 * 9) + ((3 - 4) * 5)`, which
|
||||||
|
evaluate to `85`. We represent this as a much bigger tree:
|
||||||
|
|
||||||
|
<!-- mdbook-xgettext: skip -->
|
||||||
|
|
||||||
|
```bob
|
||||||
|
.-----.
|
||||||
|
.---------------- | + | ----------------.
|
||||||
|
| '-----' |
|
||||||
|
v v
|
||||||
|
.-----. .-----.
|
||||||
|
.---- | * | ----. .---- | * | ----.
|
||||||
|
| '-----' | | '-----' |
|
||||||
|
v v v v
|
||||||
|
.------. .-----. .-----. .-----.
|
||||||
|
| 10 | | 9 | .---- | "-"| ----. | 5 |
|
||||||
|
'------' '-----' | '-----' | '-----'
|
||||||
|
v v
|
||||||
|
.-----. .-----.
|
||||||
|
| 3 | | 4 |
|
||||||
|
'-----' '-----'
|
||||||
|
```
|
||||||
|
|
||||||
|
In code, we will represent the tree with two types:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
{{#include exercise.rs:Operation}}
|
||||||
|
|
||||||
|
{{#include exercise.rs:Expression}}
|
||||||
|
```
|
||||||
|
|
||||||
The `Box` type here is a smart pointer, and will be covered in detail later in
|
The `Box` type here is a smart pointer, and will be covered in detail later in
|
||||||
the course. An expression can be "boxed" with `Box::new` as seen in the tests.
|
the course. An expression can be "boxed" with `Box::new` as seen in the tests.
|
||||||
To evaluate a boxed expression, use the deref operator (`*`) to "unbox" it:
|
To evaluate a boxed expression, use the deref operator (`*`) to "unbox" it:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user