Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use for-comprehenion / yield to create a map in Scala?

Tags:

Can I "yield" into a Map?

I've tried

val rndTrans = for (s1 <- 0 to nStates;                     s2 <- 0 to nStates                         if rnd.nextDouble() < trans_probability)                             yield (s1 -> s2); 

(and with , instead of ->) but I get the error

TestCaseGenerator.scala:42: error: type mismatch;  found   : Seq.Projection[(Int, Int)]  required: Map[State,State]     new LTS(rndTrans, rndLabeling) 

I can see why, but I can't see how to solve this :-/

like image 360
aioobe Avatar asked Nov 18 '10 10:11

aioobe


People also ask

What is the use of yield keyword in scala for comprehension?

yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer.

What is a for comprehension in scala?

Language. Scala offers a lightweight notation for expressing sequence comprehensions. Comprehensions have the form for (enumerators) yield e , where enumerators refers to a semicolon-separated list of enumerators. An enumerator is either a generator which introduces new variables, or it is a filter.

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.


1 Answers

scala> (for(i <- 0 to 10; j <- 0 to 10) yield (i -> j)) toMap res1: scala.collection.immutable.Map[Int,Int] = Map((0,10), (5,10), (10,10), (1,10), (6,10), (9,10), (2,10), (7,10), (3,10),  (8,10), (4,10)) 
like image 78
Vasil Remeniuk Avatar answered Oct 20 '22 00:10

Vasil Remeniuk