import std/io import std/list // A trait with two parameters (ADR 0018): an impl is chosen by both. trait Convert { fn convert :: x: a -> b } pub type Celsius { Celsius(Float) } pub type Fahrenheit { Fahrenheit(Float) } impl Convert { fn convert :: c { match c { Celsius(t) -> Fahrenheit(t * 9.0 / 5.0 + 32.0) } } } impl Convert { fn convert :: n { "#" <> show n } } impl Convert { fn convert :: b { if b { 1 } else { 0 } } } // The impl's own constraint is passed as a dictionary. impl Convert, List> where Convert { fn convert :: xs { list.map xs convert } } impl Convert, List> where Convert { fn convert :: o { match o { Some(x) -> [convert x], None -> [] } } } // A trait with several methods and two parameters. trait Store { fn put :: c: c k: k -> c fn has :: c: c k: k -> Bool } pub type Names { Names(List) } impl Store { fn put :: c k { match c { Names(ks) -> Names([k, ..ks]) } } fn has :: c k { match c { Names(ks) -> list.any ks fn x { x == k } } } } impl Store, Int> { fn put :: c _ { c } fn has :: c k { list.length c > k } } // A `where` clause with two parameters. pub fn labels :: xs: List -> List where Convert { convert xs } // Inferred: `fn(List) -> List where Convert`. fn convert_each :: xs { list.map xs convert } fn fill :: c keys { list.fold keys c put } pub fn main :: -> () / { let f: Fahrenheit = convert Celsius(100.0) match f { Fahrenheit(t) -> io.println (show t) } io.println (string_of (labels [1, 2, 3])) let bits: List = convert_each [True, False, True] io.println (show bits) let some: List = convert Some(7) let none: Option = None let missing: List = convert none io.println (show some <> " " <> show missing) let names = fill Names([]) ["ann", "bo"] io.println (show (has names "bo") <> " " <> show (has names "cy")) io.println (show (has [10, 20] 1) <> " " <> show (has (put [10] 5) 3)) } fn string_of :: xs: List -> String { list.fold xs "" fn acc x { acc <> x } } //> 212.0 //> #1#2#3 //> [1, 0, 1] //> [#7] [] //> True False //> True False