docs: add a recursive structure and binary tree example in the sumtype section (#8122)
parent
28ed4da1ce
commit
84de4622a4
29
doc/docs.md
29
doc/docs.md
|
@ -1884,6 +1884,35 @@ println(sum)
|
|||
The built-in method `type_name` returns the name of the currently held
|
||||
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
|
||||
|
||||
To check whether a sum type instance holds a certain type, use `sum is Type`.
|
||||
|
|
Loading…
Reference in New Issue