Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: What does mean to pass a Set to the map function of a set

Tags:

scala

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?

like image 566
ChucK Avatar asked Feb 07 '12 17:02

ChucK


People also ask

What does map () do in Scala?

map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.

How do you add a value to a map in Scala?

Solution. Add elements to a mutable map by simply assigning them, or with the += method. Remove elements with -= or --= . Update elements by reassigning them.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

How do you access map elements in Scala?

Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.


2 Answers

But I thought that the map function can only take another function not a new Set.

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.

like image 58
Jörg W Mittag Avatar answered Oct 17 '22 17:10

Jörg W Mittag


Set is also function - it extends Function1. See Inherited section in Scaladoc:

http://www.scala-lang.org/api/current/scala/collection/immutable/Set.html

like image 43
tenshi Avatar answered Oct 17 '22 17:10

tenshi