Reputation: 2134
I've just seen I can do:
Set(1, 2, 3).map(Set(1))
which yields the result:
Set(true, false)
But I thought that the map function can only take another function not a new Set. If anything I'd expect this to return a set of sets. What's going on and what does the result mean?
Upvotes: 14
Views: 5936
Reputation: 92026
Set[A]
extends Function1[A, Boolean]
. Map[K, V]
extends
PartialFunction[K, V]
which in turn extends Function1[K, V]
.Seq[A]
extends PartialFunction[Int, A]
which in turn extends
Function1[Int, A]
.So in Scala collections library, sets, sequences, and maps are themselves functions.
apply
method in Set[_]
tests set membership. apply
method in Map[_, _]
returns the value associated with the given key. Throws error if the
key is absent.apply
method in Seq[_]
returns the element at given index. Throws error for an invalid index.The following two are equivalent:
Set(1, 2, 3).map(Set(1))
Set(1, 2, 3).map(x => Set(1).contains(x))
So are the following two:
Seq(1, 2, 3).collect(someMap)
Seq(1, 2, 3) collect {
case x if someMap contains x => someMap(x)
}
And also the following two:
Seq(1, 2, 3).map(someSeq)
Seq(1, 2, 3).map(x => someSeq(x))
Upvotes: 5
Reputation: 369458
But I thought that the
map
function can only take another function not a newSet
.
A Set
is a function. It is a function from its elements to booleans: when you pass it an element, it tells you whether that element is part of the Set
.
Set(1, 2, 3).map(Set(1))
Iterates over the Set(1, 2, 3)
, passing each each element to the Set(1)
. I.e. it first asks "is 1
a member of set {1}
", which is true
, then it asks the same question for 2
and 3
, which is false
.
So, the result is Set(true, false, false)
, which of course is just Set(true, false)
.
Similarly, a sequence is a function from integers to elements, a map is a function from keys to values.
Upvotes: 20
Reputation: 26566
Set
is also function - it extends Function1
. See Inherited section in Scaladoc:
http://www.scala-lang.org/api/current/scala/collection/immutable/Set.html
Upvotes: 5