Skip to content

Commit

Permalink
I think this revision provides a better functional solution. Score st…
Browse files Browse the repository at this point in the history
…ill same though :(
  • Loading branch information
andrueastman committed Nov 10, 2016
1 parent 929b06a commit f2dc5e8
Showing 1 changed file with 13 additions and 20 deletions.
33 changes: 13 additions & 20 deletions funsets/src/main/scala/funsets/FunSets.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,31 @@ object FunSets {
/**
* Returns the set of the one given element.
*/
def singletonSet(elem: Int): Set = x => (x == elem)
def singletonSet(elem: Int): Set = x => (x == elem)


/**
* Returns the union of the two given sets,
* the sets of all elements that are in either `s` or `t`.
*/
def union(s: Set, t: Set): Set = (x:Int) => contains(s,x) || contains(t,x)

def union(s: Set, t: Set): Set = x => contains(s,x) || contains(t,x)
/**
* Returns the intersection of the two given sets,
* the set of all elements that are both in `s` and `t`.
*/
def intersect(s: Set, t: Set): Set = (x:Int) => contains(s,x) && contains(t,x)
def intersect(s: Set, t: Set): Set = x => contains(s,x) && contains(t,x)

/**
* Returns the difference of the two given sets,
* the set of all elements of `s` that are not in `t`.
*/
def diff(s: Set, t: Set): Set = (x:Int) => contains(s,x) && !contains(t,x)
def diff(s: Set, t: Set): Set = x => if(!contains(s,x)) false else !contains(t,x)

/**
* Returns the subset of `s` for which `p` holds.
*/
def filter(s: Set, p: Int => Boolean): Set = (x:Int) => contains(s,x) && contains(p,x)
def filter(s: Set, p: Int => Boolean): Set = x => if(contains(s,x)) p(x) else false


/**
Expand All @@ -54,32 +54,25 @@ object FunSets {
/**
* Returns whether all bounded integers within `s` satisfy `p`.
*/
def forall(s: Set, p: Int => Boolean): Boolean = {
def forall(s: Set, p: Int => Boolean): Boolean = {
def iter(a: Int): Boolean = {
if (a < -bound) true
else if (contains(s, a)) contains(p, a) && iter(a-1)
else iter(a-1)
if (a>bound) true
else if (s(a) && !p(a)) false
else iter(a+1)
}
iter(bound)
iter(-bound)
}

/**
* Returns whether there exists a bounded integer within `s`
* that satisfies `p`.
*/
def exists(s: Set, p: Int => Boolean): Boolean = {
def iter(a: Int): Boolean = {
if (a < -bound) true
else if (contains(s, a)) contains(p, a)
else iter(a-1)
}
iter(bound)
}
def exists(s: Set, p: Int => Boolean): Boolean = forall(filter(s,p),p)

/**
* Returns a set transformed by applying `f` to each element of `s`.
*/
def map(s: Set, f: Int => Int): Set =(y: Int) => exists(s, x => f(x) == y)
def map(s: Set, f: Int => Int): Set = x => exists(s,y=>f(y)==x)

/**
* Displays the contents of a set
Expand Down

0 comments on commit f2dc5e8

Please sign in to comment.