import std/io import std/list // User-defined derives (ADR 0019): a trait marked `@derivable f` is // derived as `f` applied to the value's constructor, each field replaced // by the trait's method applied to it. pub type Json { JNull, JInt(Int), JStr(String), JArr(List), JObj(List<(String, Json)>) } @derivable json_of_constructor trait ToJson { fn to_json :: x: a -> Json } // Records become objects, other constructors arrays tagged by name. fn json_of_constructor :: c: Constructor -> Json { match c.fields { [] -> JStr(c.name) , [f, ..] if f.label != "" -> JObj(list.map c.fields fn f { (f.label, f.value) }) , fields -> JArr([JStr(c.name), ..list.map fields fn f { f.value }]) } } impl ToJson { fn to_json :: n { JInt(n) } } impl ToJson { fn to_json :: s { JStr(s) } } impl ToJson> where ToJson { fn to_json :: xs { JArr(list.map xs to_json) } } fn render :: j: Json -> String { match j { JNull -> "null" , JInt(n) -> show n , JStr(s) -> "\"" <> s <> "\"" , JArr(items) -> "[" <> join (list.map items render) <> "]" , JObj(entries) -> "\{" <> join (list.map entries fn e { "\"" <> e.0 <> "\": " <> render e.1 }) <> "\}" } } fn join :: xs: List -> String { match xs { [] -> "", [x] -> x, [x, ..rest] -> x <> ", " <> join rest } } // A second derivable trait, with an Int result: the number of nodes. @derivable count_nodes trait Size { fn size :: x: a -> Int } fn count_nodes :: c: Constructor -> Int { list.fold c.fields 1 fn n f { n + f.value } } impl Size { fn size :: _ { 1 } } @derive ToJson Show pub type User { User(name: String, age: Int, tags: List) } @derive ToJson Size pub type Shape { Dot, Circle(Int), Rect(Int, Int) } // Generic: requires the trait of its parameter; recursive through it. @derive ToJson Size Debug pub type Tree { Leaf, Node(Tree, a, Tree) } pub fn main :: -> () / { let ann = User("ann", 41, ["admin", "ops"]) io.println (render (to_json ann)) io.println (show ann) io.println (render (to_json [Dot, Circle(2), Rect(3, 4)])) let tree = Node(Node(Leaf, 1, Leaf), 2, Leaf) io.println (render (to_json tree)) io.println (debug tree) io.println ( show (size tree) <> " " <> show (size Rect(3, 4)) <> " " <> show (size Dot) ) } //> {"name": "ann", "age": 41, "tags": ["admin", "ops"]} //> User(ann, 41, [admin, ops]) //> ["Dot", ["Circle", 2], ["Rect", 3, 4]] //> ["Node", ["Node", "Leaf", 1, "Leaf"], 2, "Leaf"] //> Node(Node(Leaf, 1, Leaf), 2, Leaf) //> 7 3 1