From 84de4622a418e1290cd3ba932eaf255a43943064 Mon Sep 17 00:00:00 2001 From: Ruofan XU <47302112+SleepyRoy@users.noreply.github.com> Date: Sun, 17 Jan 2021 23:27:22 +0800 Subject: [PATCH] docs: add a recursive structure and binary tree example in the sumtype section (#8122) --- doc/docs.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) 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`.