1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::collections::{HashSet,BTreeSet};
use std::borrow::Borrow;
use std::hash::Hash;

/// basic protocol for sets.
pub trait Set<T> where Self:Sized {
    /// a set maps from items to themselves.
    fn fun<'a,Q:?Sized>(&'a self) -> Box<Fn(&Q) -> Option<&'a T> + 'a> where T:Borrow<Q>, Q:Hash+Ord;

    /// adds item `i`.
    ///
    /// like `clojure`'s [`conj`](http://clojuredocs.org/clojure.core/conj).
    fn inc(self, i:T) -> Self;

    /// removes item `i`.
    ///
    /// like `clojure`'s [`disj`](http://clojuredocs.org/clojure.core/disj).
    fn dec<Q:?Sized>(self, i:&Q) -> Self where T:Borrow<Q>, Q:Hash+Ord;

    /// pours another collection into this one.
    ///
    /// like `clojure`'s [`into`](http://clojuredocs.org/clojure.core/into).
    fn plus<I>(self, coll:I) -> Self where I:IntoIterator<Item = T>
    {coll.into_iter().fold(self, Set::inc)}

    /// `clear`.
    fn zero(self) -> Self;

    /// `shrink_to_fit`.
    fn shrink(self) -> Self;
}

impl<T> Set<T> for HashSet<T> where T:Hash+Eq {
    fn fun<'a,Q:?Sized>(&'a self) -> Box<Fn(&Q) -> Option<&'a T> + 'a> where T:Borrow<Q>, Q:Hash+Eq
    {Box::new(move |i| self.get(i))}

    fn inc(mut self, i:T) -> Self
    {self.insert(i); self}

    fn dec<Q:?Sized>(mut self, i:&Q) -> Self where T:Borrow<Q>, Q:Hash+Eq
    {self.remove(i); self}

    fn zero(mut self) -> Self
    {self.clear(); self}

    fn shrink(mut self) -> Self
    {self.shrink_to_fit(); self}
}

impl<T> Set<T> for BTreeSet<T> where T:Ord {
    fn fun<'a,Q:?Sized>(&'a self) -> Box<Fn(&Q) -> Option<&'a T> + 'a> where T:Borrow<Q>, Q:Ord
    {Box::new(move |i| self.get(i))}

    fn inc(mut self, i:T) -> Self
    {self.insert(i); self}

    fn dec<Q:?Sized>(mut self, i:&Q) -> Self where T:Borrow<Q>, Q:Ord
    {self.remove(i); self}

    fn zero(mut self) -> Self
    {self.clear(); self}

    fn shrink(self) -> Self
    {self}
}