scala - Scala 中函数类型的类型别名
问题描述
我是最新的 Scala 语言,但我不明白它是如何type Set = Int => Boolean
工作的。我知道这是与布尔值转换的整数。我有def map(s: Set, f: Int => Int): Set = y => exists(s, x => y == f(x))
For 存在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
的每个元素都是 x 元素s
,f(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)))
解决方案
鉴于map()
实施...
y => exists(s, x => y == f(x))
...和调用...
map(Set(2,3,5), (i: Int) => i * 20)
...做一些替换,你会得到:
val mappedSet = y => exists(Set(2,3,5), x => y == x*20)
作为 a Set
is Int => Boolean
(一个接受 anInt
并返回true或false的函数),mappedSet
是一个要求:
给定一个数字 ,y
在 +-bounds 中是否存在一个既通过(是其中的成员)Set(2,3,5)
并且当乘以 20 时等于 的数字y
?
mappedSet(60)
返回true因为在 +-bounds 内确实存在一个数字 ,3
它既是Set(2,3,5)
AND 的成员,当乘以 20 时,等于60
。
mappedSet(80)
返回false,因为找不到通过这两个测试的数字。
推荐阅读
- python - 如何格式化观察到的数据以在 pymc3 中用于贝叶斯网络?
- r - 如何在多个数据帧上实现多个相同的功能并将输出检索到多个数据帧
- apache-kafka - 我们可以将消息重新发送到多个 Kafka 分区吗
- python - 使用 Python 抓取 ASPX 页面
- mongodb - 如何使用 db.adminCommand("top") 访问 json 部分
- amazon-web-services - 通过用户订阅获得推荐
- python - 复选框检测opencv
- angular - Angular - 动态加载的模块/组件中的更改检测而不使用`ChangeDetectorRef`
- arrays - 在c中对0与字符串“hello world”进行异或运算
- c++ - 是否有可以处理更改哈希/比较/相等方法的 C++ 容器?