// `std/collection` (ADR 0047): one trait over List, Array, Dict and // Bytes, with an associated element type, and generic helpers on it. import std/array import std/bytes import std/collection.{type Collection, type Elem} import std/dict import std/io import std/iter // Generic: works on any collection whose elements show. fn describe :: c: c -> String where Collection, Show> { "{collection.size c} elements: {collection.to_list c}" } // Generic, through the lazy iterator. fn doubled_total :: c: c -> Int where Collection { collection.iter c |> iter.map fn x { x * 2 } |> iter.fold 0 fn a x { a + x } } pub fn main :: -> () / { let xs = [3, 1, 4, 1, 5] let arr = array.from_list [2, 7, 1] let d = dict.from_list [("b", 2), ("a", 1)] let b = bytes.from_list [0, 255, 16] io.println (describe xs) io.println (describe arr) io.println (describe d) io.println (describe b) io.println (show [collection.sum xs, collection.sum arr, collection.sum b]) io.println (show (collection.sum [1.5, 2.25])) io.println (show (collection.count xs fn x { x == 1 })) io.println (show [collection.contains arr 7, collection.contains b 1]) io.println (show (collection.contains d ("a", 1))) io.println (show [collection.is_empty xs, collection.is_empty (dict.empty ())]) io.println (show (collection.fold d "" fn acc kv { acc <> kv.0 })) io.println (show [doubled_total xs, doubled_total b]) } //> 5 elements: [3, 1, 4, 1, 5] //> 3 elements: [2, 7, 1] //> 2 elements: [(a, 1), (b, 2)] //> 3 elements: [0, 255, 16] //> [14, 10, 271] //> 3.75 //> 2 //> [True, False] //> True //> [False, True] //> ab //> [28, 542]