// A multi-shot resumption taken in the middle of a `map` (ADR 0039, ADR // 0017): each resumption builds its own list, so a context both share is // copied before it changes. Same lists, in the same order, on both // backends. import std/io import std/list effect amb { multi ctl choose :: -> Bool } fn all :: action: fn() -> a / -> List / { handle { [action ()] } with { choose -> list.append (resume True) (resume False) } } /// Each element doubled or not: 2^3 lists, built by `map`. fn choices :: xs: List -> List> { all fn { list.map xs fn x { if choose () { x * 2 } else { x } } } } /// The same, with a `map` inside a `map`'s mapper. fn nested :: -> List>> { all fn { list.map [1, 2] fn x { list.map [10, 20] fn y { if choose () { x + y } else { 0 } } } } } pub fn main :: -> () / { list.each (choices [1, 2, 3]) fn l { io.println "{l}" } let n = nested () match (n, list.reverse n) { ([first, ..], [last, ..]) -> io.println "{list.length n} {first} {last}" , _ -> io.println "none" } } //> [2, 4, 6] //> [2, 4, 3] //> [2, 2, 6] //> [2, 2, 3] //> [1, 4, 6] //> [1, 4, 3] //> [1, 2, 6] //> [1, 2, 3] //> 16 [[11, 21], [12, 22]] [[0, 0], [0, 0]]