// *+ 和 ** 的优先级相同 scala> a *+ b ** a res11: X = ((2*+3)**2)
scala> a ** b *+ a res12: X = ((2**3)*+2)
// *+ 的优先级高于 ** scala> a *+ b +* a res13: X = ((2*+3)+*2)
scala> a +* b *+ a res14: X = (2+*(3*+2))
那么,下述表达式的计算顺序如何?
a + b ^? c ?^ d less a ==> b | c
其中 a, b, c这三者代表变量,其他的字符都是运算符
对照上表,依次加上括号
1 2 3 4 5 6
a + b ^? c ?^ d less a ==> b | c = a + b ^? (c ?^ d) less a ==> b | c = (a+b) ^? (c ?^ d) less a ==> b | c = (a + b) ^? (c ?^ d) less (a ==> b) | c = ((a + b) ^? (c ?^ d)) less (a ==> b) | c = ((a + b) ^? (c ?^ d)) less ((a ==> b) | c)
objectFunSets{ typeSet= Int => Boolean defcontains(s: Set: elem: Int): Boolean = s(elem) defsingletonSet(elem: Int): Set = ??? /** * Displays the contents of a set */ deftoString(s: Set): String = { val xs = for (i <- -bound to bound if contains(s, i)) yield i xs.mkString("{", ",", "}") }
/** * Prints the contents of a set on the console. */ defprintSet(s: Set) { println(toString(s)) } }
/** * Returns the set of the one given element. */ defsinlgetonSet(elem: Int): Set = x: Int => (x == elem)
接下来我们需要实现集合的∩/∪/差集
求S和T的差集: S - T = {x | x ∈ S & x ∉ T}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Returns the union of the two given sets, * the sets of all elements that are in either `s` or `t`. */ defunion(s: Set, t: Set): Set = x: Int => 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`. */ defintersect(s: Set, t: Set): Set = (x:Int) => 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`. */ defdiff(s: Set, t: Set): Set = (x:Int) => contains(s, x) && !contains(t, x)
实现集合的过滤函数
1 2 3 4
/** * Returns the subset of `s` for which `p` holds. */ deffilter(s: Set, p: Int => Boolean): Set = (x: Int) => contains(s, x) && p(x)
判断集合中的所有元素是否满足条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/** * The bounds for `forall` and `exists` are +/- 1000. */ val bound = 1000
/** * Returns whether all bounded integers within `s` satisfy `p`. */ defforall(s: Set, p: Int => Boolean): Boolean = { defiter(a: Int): Boolean = { if (contains(x, a) && !p(a)) false elseif (a > bound) true else iter(a + 1) } iter(-bound) }
/** * Returns whether there exists a bounded integer within `s` * that satisfies `p`. */ defexists(s: Set, p: Int => Boolean): Boolean = !forall(s, x => !p(x))
对集合中的每个元素做变换操作
1 2 3 4
/** * Returns a set transformed by applying `f` to each element of `s`. */ defmap(s: Set, f: Int => Int): Set = (x: Int) => exists(s, (y: Int) => x == f(y))
这个实现是比较不那么容易理解
先看exist(s, (y: Int) => x == f(y))这个部分
对于旧的Set s, 我们希望对其每个元素
新的Set t = {ne | e ∈ s, ne = f(e)}
这个形式是不是和上面的很像?其实就是数学语言的一个转换
如果还是不明白,可以考虑代入具体的值,假如s = 2 => true, f = (x: Int) => 2 * x
t = map(s, f) = (x: Int) => exist(x, (y: int) => x == 2 * y)