2010-11-18 11 views
16

私はマップに "降伏"できますか?for-comprehenion/yieldを使用してScalaで地図を作成できますか?

私はなぜ見ることができますが、私はこの問題を解決する方法を見ることができない私は

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) 

を取得:/

答えて

15
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)) 
+0

私が探しているものにおそらく近いうーん、私は得る: 'エラー:値toMapではありませんSeq.Projectionのメンバー[(Int、Int)] ' – aioobe

+0

それは変です。 Scalaのどのバージョンを使用していますか? – aioobe

+0

2.8.0.finalを使用しています –

4

代替(は2.):

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

素晴らしい今は2.7で立ち往生していますので、これを使用します。 – aioobe

12

スカラ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> 
+7

+1の神秘的な(しかし有用!)breakOut。私が間違っている場合は私を修正しますが、後で変換される別のコレクションを作成するのではなく、マップの直接生成を可能にするビルダーを提供するため、パフォーマンスが少し向上します。 –

+2

@Zwirbあなたは正しいです。そして+1は、あなたが/ yieldの構文でそれを使うことができないことを知っていたからです! :-) –

1
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]]) 
関連する問題