import std/io import std/list import std/ref // Multi-shot resumptions over cells reused in place (issue #217): the // copies of a continuation hold the same cells, so an `@fip` function in // one copy must not update them under the other. A cleanup runs once per // copy, and a region's references are shared by the copies and end after // the last one. @derive Show pub type Tree { Leaf, Node(Tree, Int, Tree) } effect amb { multi ctl choose :: -> Bool } @fip fn mirror :: t: Tree -> Tree { match t { Leaf -> Leaf, Node(l, k, r) -> Node(mirror r, k, mirror l) } } fn all :: action: fn() -> a / -> List / { handle { [action ()] } with { choose -> list.append (resume True) (resume False) } } fn sample :: -> Tree { Node(Node(Leaf, 1, Leaf), 2, Node(Leaf, 3, Leaf)) } fn root_plus :: t: Tree n: Int -> Int { match t { Node(_, k, _) -> k + n, Leaf -> n } } pub fn main :: -> () / { // Built before the choice: each copy mirrors the same cells. let mirrored = all fn { let t = sample () if choose () { mirror t } else { mirror (mirror t) } } io.println "{mirrored}" // A second choice clones a copy that has reused cells already. let twice = all fn { let t = mirror (sample ()) let u = if choose () { mirror t } else { t } if choose () { mirror u } else { u } } io.println "{twice}" // With a cleanup and a region in the copied continuation. let counted = all fn { defer io.println "copy done" region { let seen = ref.new 0 let t = sample () let t = if choose () { mirror t } else { t } ref.set seen (ref.get seen + 1) let n = ref.get seen root_plus (mirror t) n } } io.println "{counted}" } //> [Node(Node(Leaf, 3, Leaf), 2, Node(Leaf, 1, Leaf)), Node(Node(Leaf, 1, Leaf), 2, Node(Leaf, 3, Leaf))] //> [Node(Node(Leaf, 3, Leaf), 2, Node(Leaf, 1, Leaf)), Node(Node(Leaf, 1, Leaf), 2, Node(Leaf, 3, Leaf)), Node(Node(Leaf, 1, Leaf), 2, Node(Leaf, 3, Leaf)), Node(Node(Leaf, 3, Leaf), 2, Node(Leaf, 1, Leaf))] //> copy done //> copy done //> [3, 4]