diff --git a/doc/docs.md b/doc/docs.md index 2de7e7df37..5785c217e9 100644 --- a/doc/docs.md +++ b/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`.