docs: add a recursive structure and binary tree example in the sumtype section (#8122)

pull/8172/head
Ruofan XU 2021-01-17 23:27:22 +08:00 committed by GitHub
parent 28ed4da1ce
commit 84de4622a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 29 additions and 0 deletions

View File

@ -1884,6 +1884,35 @@ println(sum)
The built-in method `type_name` returns the name of the currently held The built-in method `type_name` returns the name of the currently held
type. type.
With sum types you could build recursive structures and write concise but powerful code on them.
```v
// V's binary tree
struct Empty {}
struct Node {
value f64
left Tree
right Tree
}
type Tree = Empty | Node
// sum up all node values
fn sum(tree Tree) f64 {
return match tree {
Empty { f64(0) } // TODO: as match gets smarter just remove f64()
Node { tree.value + sum(tree.left) + sum(tree.right) }
}
}
fn main() {
left := Node{0.2, Empty{}, Empty{}}
right := Node{0.3, Empty{}, Node{0.4, Empty{}, Empty{}}}
tree := Node{0.5, left, right}
println(sum(tree)) // 0.2 + 0.3 + 0.4 + 0.5 = 1.4
}
```
#### Dynamic casts #### Dynamic casts
To check whether a sum type instance holds a certain type, use `sum is Type`. To check whether a sum type instance holds a certain type, use `sum is Type`.