/// Collections of elements (ADR 0047): what every container in std /// offers, for code that works on any of them. /// /// import std/collection /// /// collection.size(dict) // as dict.size(dict) /// collection.sum([1, 2, 3]) // 6 /// collection.contains(bytes, 0) // works on any collection /// /// Each container's own module keeps its functions; this module adds /// the generic ones. A collection's element type is `Elem`: `a` for /// `List` and `Array`, `(k, v)` for `Dict`, `Int` for `Bytes`. import std/array.{type Array} import std/bytes import std/dict.{type Dict} import std/iter.{type Iter} import std/list pub trait Collection { /// What it holds. type Elem /// How many elements it holds. fn size :: c: c -> Int /// Combine the elements, in order. fn fold :: c: c acc: b f: fn(b, Elem) -> b / -> b / /// The elements, in order. fn to_list :: c: c -> List> /// The elements, in order, as a lazy iterator. fn iter :: c: c -> Iter, e> } impl Collection> { type Elem = a fn size :: c { list.length c } fn fold :: c acc f { list.fold c acc f } fn to_list :: c { c } fn iter :: c { iter.from_list c } } impl Collection> { type Elem = a fn size :: c { array.length c } fn fold :: c acc f { array.fold c acc f } fn to_list :: c { array.to_list c } fn iter :: c { iter.from_list (array.to_list c) } } impl Collection> { type Elem = (k, v) fn size :: c { dict.size c } fn fold :: c acc f { dict.fold c acc fn a k v { f a (k, v) } } fn to_list :: c { dict.to_list c } fn iter :: c { iter.from_list (dict.to_list c) } } impl Collection { type Elem = Int fn size :: c { bytes.length c } fn fold :: c acc f { list.fold (bytes.to_list c) acc f } fn to_list :: c { bytes.to_list c } fn iter :: c { iter.from_list (bytes.to_list c) } } /// Whether it holds no element. pub fn is_empty :: c: c -> Bool where Collection { size c == 0 } /// How many elements satisfy `keep`. pub fn count :: c: c keep: fn(Elem) -> Bool / -> Int / where Collection { fold c 0 fn n x { if keep x { n + 1 } else { n } } } /// Whether it holds `x`. pub fn contains :: c: c x: Elem -> Bool where Collection, Eq> { fold c False fn found y { found || y == x } } /// The sum of its elements; `default()` (0) when it is empty. pub fn sum :: c: c -> Elem where Collection, Num>, Default> { fold c (default ()) fn total x { total + x } }