代码之家  ›  专栏  ›  技术社区  ›  aioobe

我能用Scala来理解/产生一个地图吗?

  •  16
  • aioobe  · 技术社区  · 14 年前

    我能“屈服”成地图吗?

    我试过了

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

    (和 , 而不是 -> )但我明白了

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

    我知道为什么,但我不知道如何解决这个问题:-/

    4 回复  |  直到 14 年前
        1
  •  18
  •   Vasil Remeniuk    14 年前
    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
  •  13
  •   Eastsun    14 年前

    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
  •  5
  •   aioobe    14 年前

    替代方案( 在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
  •  1
  •   AlexY    8 年前
    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]])
    
    推荐文章