import std/io import std/list // Pipes and captures (ADR 0023): `x |> f(a)` is `f(x, a)`, // `x |> f(a, _)` is `f(a, x)`, and `f(a, _)` alone is `fn(v) { f(a, v) }`. fn sub :: x: Int y: Int -> Int { x - y } fn greet :: ~greeting: String ~name: String -> String { greeting <> ", " <> name } /// Prints `label` and returns `x`: shows the evaluation order. fn trace :: label: String x: a -> a / { io.println label x } fn sum_to :: n: Int acc: Int -> Int { // A pipe in tail position stays a tail call. if n == 0 { acc } else { acc + n |> sum_to (n - 1) _ } } fn subtract_from :: x: Int { fn y { x - y } } fn pick :: { io.println "callee" sub } pub fn main :: -> () / { // Argument placing. io.println (show (10 |> sub 3)) io.println (show (10 |> sub 3 _)) io.println (show (10 |> sub _ 3)) io.println ("Ada" |> greet ~greeting: "Hello" ~name: _) io.println (greet ~greeting: "Hi" ~name: "Grace") io.println (show ([1, 2, 3] |> list.map (sub 10 _) |> list.sum)) // The left side is evaluated first, as written. let r = trace "left" 5 |> sub (trace "argument" 1) _ io.println (show r) let r = trace "left" 5 |> (pick ()) 1 io.println (show r) // A function returned by a call: place the value explicitly. let r = trace "left" 5 |> (subtract_from (trace "argument" 1)) _ io.println (show r) // Captures: the other arguments are evaluated at each call. let minus = sub (trace "captured" 100) _ io.println "made" io.println (show (minus 1 + minus 2)) list.each ["x", "y"] (io.println _) io.println (show (list.map [1, 2] Some(_))) io.println (show (sum_to 1000000 0)) } //> 7 //> -7 //> 7 //> Hello, Ada //> Hi, Grace //> 24 //> left //> argument //> -4 //> left //> callee //> 4 //> left //> argument //> -4 //> made //> captured //> captured //> 197 //> x //> y //> [Some(1), Some(2)] //> 500000500000