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

試著忘記壹切 提交于 2019-12-08 23:39:26

问题


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 :-/


回答1:


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))



回答2:


An alternate solution in Scala 2.8:

Welcome to Scala version 2.8.1.r23457-b20101106033551 (Java HotSpot(TM) Client VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.collection.breakOut            
import scala.collection.breakOut

scala> val list: List[(Int,Int)] = (for(i<-0 to 3;j<-0 to 2) yield(i->j))(breakOut)
list: List[(Int, Int)] = List((0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2), (3,0), (3,1), (3,2))

scala> val map: Map[Int,Int] = (for(i<-0 to 3;j<-0 to 2) yield(i->j))(breakOut)    
map: Map[Int,Int] = Map((0,2), (1,2), (2,2), (3,2))

scala> val set: Set[(Int,Int)] = (for(i<-0 to 3;j<-0 to 2) yield(i->j))(breakOut)
set: Set[(Int, Int)] = Set((2,2), (3,2), (0,1), (1,2), (0,0), (2,0), (3,1), (0,2), (1,1), (2,1), (1,0), (3,0))

scala> 



回答3:


Alternative (works on 2.7):

scala> Map((for(i <- 0 to 10; j <- 0 to 10) yield (i -> j)): _*)
res0: 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))



回答4:


val rndTrans = (
  for {
    s1 <- 0 to nStates
    s2 <- 0 to nStates if rnd.nextDouble() < trans_probability
  } yield s1 -> s2
  ) (collection.breakOut[Any, (Int, Int), Map[Int, Int]])


来源:https://stackoverflow.com/questions/4213992/can-i-use-for-comprehenion-yield-to-create-a-map-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!