protocoll/
_set.rs

1use std::collections::{HashSet,BTreeSet};
2use std::borrow::Borrow;
3use std::hash::Hash;
4
5/// basic protocol for sets.
6pub trait Set<T> where Self:Sized {
7    /// a set maps from items to themselves.
8    fn fun<'a,Q:?Sized>(&'a self) -> Box<Fn(&Q) -> Option<&'a T> + 'a> where T:Borrow<Q>, Q:Hash+Ord;
9
10    /// adds item `i`.
11    ///
12    /// like `clojure`'s [`conj`](http://clojuredocs.org/clojure.core/conj).
13    fn inc(self, i:T) -> Self;
14
15    /// removes item `i`.
16    ///
17    /// like `clojure`'s [`disj`](http://clojuredocs.org/clojure.core/disj).
18    fn dec<Q:?Sized>(self, i:&Q) -> Self where T:Borrow<Q>, Q:Hash+Ord;
19
20    /// pours another collection into this one.
21    ///
22    /// like `clojure`'s [`into`](http://clojuredocs.org/clojure.core/into).
23    fn plus<I>(self, coll:I) -> Self where I:IntoIterator<Item = T>
24    {coll.into_iter().fold(self, Set::inc)}
25
26    /// `clear`.
27    fn zero(self) -> Self;
28
29    /// `shrink_to_fit`.
30    fn shrink(self) -> Self;
31}
32
33impl<T> Set<T> for HashSet<T> where T:Hash+Eq {
34    fn fun<'a,Q:?Sized>(&'a self) -> Box<Fn(&Q) -> Option<&'a T> + 'a> where T:Borrow<Q>, Q:Hash+Eq
35    {Box::new(move |i| self.get(i))}
36
37    fn inc(mut self, i:T) -> Self
38    {self.insert(i); self}
39
40    fn dec<Q:?Sized>(mut self, i:&Q) -> Self where T:Borrow<Q>, Q:Hash+Eq
41    {self.remove(i); self}
42
43    fn zero(mut self) -> Self
44    {self.clear(); self}
45
46    fn shrink(mut self) -> Self
47    {self.shrink_to_fit(); self}
48}
49
50impl<T> Set<T> for BTreeSet<T> where T:Ord {
51    fn fun<'a,Q:?Sized>(&'a self) -> Box<Fn(&Q) -> Option<&'a T> + 'a> where T:Borrow<Q>, Q:Ord
52    {Box::new(move |i| self.get(i))}
53
54    fn inc(mut self, i:T) -> Self
55    {self.insert(i); self}
56
57    fn dec<Q:?Sized>(mut self, i:&Q) -> Self where T:Borrow<Q>, Q:Ord
58    {self.remove(i); self}
59
60    fn zero(mut self) -> Self
61    {self.clear(); self}
62
63    fn shrink(self) -> Self
64    {self}
65}