scala set.contains 的实现 [英] Implementation of scala set.contains
问题描述
type Set = Int => Boolean
/**
* Indicates whether a set contains a given element.
*/
def contains(s: Set, elem: Int): Boolean = s(elem)
为什么这个 contains
函数有效?
Why does this contains
function work?
我不明白.()
操作符如何返回 true
/false
关于这个元素在集合中的存在?
I don't get it.
How does the ()
operator return true
/false
about existence of this element in set?
推荐答案
从这一点来看,第一行的类型别名意味着我们可以将第二行改写如下:
Taking this piece by piece, the type alias in the first line means that we can rewrite the second line as follows:
def contains(s: Int => Boolean, elem: Int): Boolean = s(elem)
但是 A =>B
只是 Function1[A, B]
,所以我们可以做更多的重写:
But A => B
is just syntactic sugar for Function1[A, B]
, so we can do more rewriting:
def contains(s: Function1[Int, Boolean], elem: Int): Boolean = s(elem)
s(elem)
也是语法糖——每当你以这种方式应用"一个值到一个值时,Scala 会将它脱糖为 s.apply(elem)
:
s(elem)
is also syntactic sugar—any time you "apply" a value to a value in this way, Scala desugars it to s.apply(elem)
:
def contains(s: Function1[Int, Boolean], elem: Int): Boolean = s.apply(elem)
如果你看看 Function1
上的 apply
方法你会看到类型排列起来.
And if you look at the apply
method on Function1
you'll see that the types line up.
就是这样——我们只是将集合表示为其指标函数,然后将其埋在三层语法糖之下.
So that's it—we're just representing the set as its indicator function and then burying that under three layers of syntactic sugar.
更新以解决评论:将集合表示为其指标函数可以比通常的基于列表的表示更自然地对无限集合(以及许多其他集合)进行建模.例如,假设我想要一组所有奇数.使用您在此处的表示,这很容易:
Update to address the comment: representing a set as its indicator function makes it possible to model infinite sets (and lots of other sets) much more naturally than the usual list-based representation. Suppose I want a set of all odd numbers, for example. Using the representation you have here, this is easy:
val odds: Set[Int] = (_ % 2 != 0)
例如,尝试用 HashSet
做同样的事情.
Try doing the same thing with HashSet
, for example.
这篇关于scala set.contains 的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!