import std/io import std/list import std/string // Higher-kinded trait parameters (ADR 0018): `f` stands for a type // constructor, such as `List`, `Option` or `Result`. The row variable // `e` makes `map` accept effectful functions. trait Functor { fn map :: x: f g: fn(a) -> b / -> f / } impl Functor { fn map :: xs g { list.map xs g } } impl Functor` maps over errors. impl Functor> { fn map :: r g { match r { Ok(x) -> Ok(x), Error(e) -> Error(g e) } } } trait Monad { fn pure :: x: a -> m fn bind :: x: m g: fn(a) -> m / -> m / } impl Monad { fn pure :: x { [x] } fn bind :: xs g { match xs { [] -> [], [x, ..rest] -> list.append (g x) (bind rest g) } } } impl Monad, f) } impl Functor> where Functor { fn map :: t g { match t { Twice(x, y) -> Twice(map x g, map y g) } } } // Generic over any Functor. pub fn double_all :: x: f -> f where Functor { map x fn n { n * 2 } } // Inferred: `fn(a, fn(b) -> b / ) -> a / where Functor`. fn twice_map :: x g { map (map x g) g } // Generic over any Monad. pub fn combine :: x: m y: m f: fn(a, b) -> c -> m where Monad { bind x fn a { bind y fn b { pure (f a b) } } } fn parse_digit :: s: String -> Result { match s { "0" -> Ok(0), "1" -> Ok(1), "2" -> Ok(2), _ -> Error(s) } } pub fn main :: -> () / { io.println (show (double_all [1, 2, 3])) io.println (show (double_all Some(21))) let failed: Result = Error(5) io.println (show (double_all failed)) io.println (show (twice_map [1, 2] fn n { n + 10 })) match map Twice([1], [2, 3]) fn n { n * 100 } { Twice(a, b) -> io.println (show a <> " " <> show b) } // An effectful function: `map` performs its effects. let lengths = map ["a", "bcd"] fn s { io.println ("visiting " <> s) string.length s } io.println (show lengths) io.println (show (combine [1, 2] ["x", "y"] fn n s { show n <> s })) let none: Option = None io.println (show (combine Some(1) none fn a b { a + b })) io.println (show (combine Some(1) Some(2) fn a b { a + b })) // Recover from a parse error by trying a fallback. let parsed = bind (parse_digit "x") fn bad { parse_digit "2" } io.println (show parsed) io.println (show (map (parse_digit "y") fn bad { "not a digit: " <> bad })) } //> [2, 4, 6] //> Some(42) //> Error(10) //> [21, 22] //> [100] [200, 300] //> visiting a //> visiting bcd //> [1, 3] //> [1x, 1y, 2x, 2y] //> None //> Some(3) //> Ok(2) //> Error(not a digit: y)