【发布时间】:2021-11-06 11:48:17
【问题描述】:
我是 Scala 语言的新人,但我无法理解 type Set = Int => Boolean 的工作原理。我知道这是与布尔值转换的整数。我有def map(s: Set, f: Int => Int): Set = y => exists(s, x => y == f(x)) 存在def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, i => !p(i))) 和
def forall(s: Set, p: Int => Boolean): Boolean = {
def iter(a: Int): Boolean = {
if (a > bound) true
else if (diff(s,p)(a)) false
else iter(a + 1)
}
iter(-bound)
}
这两个函数我理解,但是map 函数我有问题。如果我称它为 map(Set(2,3,5), i => i * 20),我只是不明白它是如何显示答案的。我得到{40,60,100}。我试图理解它,我知道x 是s 中的每个元素,f(x) 是 x 元素,乘以 20。y 的范围从 -1000 到 1000 (bound = 1000)。我读这个函数是这样的:y is range -1000..1000 in exists function is getting our Set(2,3,5) and after it give somthing with Boolean type.我如何得到像{40,60,100} 这样的答案。新系列是如何在那里创建的?
完整代码->
type Set = Int => Boolean
def contains(s: Set, elem: Int): Boolean = s(elem)
def diff(s: Set, t: Set): Set = (i: Int) => s(i) && !t(i)
val bound = 1000
def forall(s: Set, p: Int => Boolean): Boolean = {
def iter(a: Int): Boolean = {
if (a > bound) true
else if (diff(s,p)(a)) false
else iter(a + 1)
}
iter(-bound)
}
def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, x => !p(x))
def map(s: Set, f: Int => Int): Set = y => exists(s, x => y == f(x))
def toString(s: Set): String = {
val xs = for (i <- -bound to bound if contains(s, i)) yield i
xs.mkString("{", ",", "}")
}
println(toString(map(Set(2, 3, 5), (i: Int) => i * 20)))
【问题讨论】:
标签: scala function types functional-programming alias