diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2013-04-10 15:05:28 +0200 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-10 18:03:23 +0100 |
commit | 32021a0347c4f364a3407ced8455dff139b18adb (patch) | |
tree | 898a3508b24f1505c5324729bb4be6e0f761a6c7 /Scala/funsets/src/main/scala | |
parent | c09ffb13d5d3e2d13b336ffc455dd2b2307f7f37 (diff) | |
download | coursera-32021a0347c4f364a3407ced8455dff139b18adb.zip coursera-32021a0347c4f364a3407ced8455dff139b18adb.tar.gz |
Scala : week2: implement forall, exists, map
Diffstat (limited to 'Scala/funsets/src/main/scala')
-rw-r--r-- | Scala/funsets/src/main/scala/funsets/FunSets.scala | 22 |
1 files changed, 12 insertions, 10 deletions
diff --git a/Scala/funsets/src/main/scala/funsets/FunSets.scala b/Scala/funsets/src/main/scala/funsets/FunSets.scala index 15a6bfc..99b0748 100644 --- a/Scala/funsets/src/main/scala/funsets/FunSets.scala +++ b/Scala/funsets/src/main/scala/funsets/FunSets.scala @@ -20,25 +20,25 @@ 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 => s(x) | t(x)) + def union(s: Set, t: Set): Set = x => s(x) | 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 => s(x) & t(x)) + def intersect(s: Set, t: Set): Set = x => s(x) & 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 => s(x) & !t(x)) + def diff(s: Set, t: Set): Set = x => s(x) & !t(x) /** * Returns the subset of `s` for which `p` holds. @@ -56,23 +56,25 @@ object FunSets { */ def forall(s: Set, p: Int => Boolean): Boolean = { def iter(a: Int): Boolean = { - if (???) ??? - else if (???) ??? - else iter(???) + if (a > bound) true + else if (contains(s, a) && !p(a)) false + else iter(a + 1) } - iter(???) + iter(-bound) } /** * Returns whether there exists a bounded integer within `s` * that satisfies `p`. */ - def exists(s: Set, p: Int => Boolean): Boolean = ??? + // elements of s do NOT all NOT satisfy p + def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, x => !p(x)) /** * Returns a set transformed by applying `f` to each element of `s`. */ - def map(s: Set, f: Int => Int): Set = ??? + // x is in S' if exists y in S so that f(y) = x + def map(s: Set, f: Int => Int): Set = x => exists(s, y => f(y) == x) /** * Displays the contents of a set |