scala的for迴圈yield值
阿新 • • 發佈:2018-12-23
2017-07-22
概述
scala語言的for語法很靈活. 除了普通的直接對集合的迴圈, 以及迴圈中的判斷和值返回. 非常靈活.
for 可以通過yield(生產)返回值, 最終組成for迴圈的物件型別.for 迴圈中的 yield 會把當前的元素記下來,儲存在集合中,迴圈結束後將返回該集合。如果被迴圈的是 Map,返回的就是Map,被迴圈的是 List,返回的就是List,以此類推。
守衛( guards) (for loop ‘if’ conditions)
可以在 for 迴圈結構中加上 ‘if’ 表示式, 和yield聯合起來用.
普通對集合或迭代迴圈
scala> for(i<- 1 to 5) println(i)
1
2
3
4
5
scala> for(i<- 1 until 5) println(i)
1
2
3
4
yield返回值
scala> for (i <- 1 to 5) yield i
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)
scala> val a= for (i <- 1 to 5) yield i
a: scala.collection.immutable.IndexedSeq[Int] = Vector (1, 2, 3, 4, 5)
scala> a
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)
scala> val a= for (i <- 1 until 5) yield i
a: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4)
scala> a
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4 )
scala> val a= for (i <- 1 until 5) yield i*2
a: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8)
scala> val a = Array(1, 2, 3, 4, 5)
a: Array[Int] = Array(1, 2, 3, 4, 5)
scala> for ( e <- a) yield e
res3: Array[Int] = Array(1, 2, 3, 4, 5)
迴圈過濾 if 判斷, 並返回值
scala> for ( e <- a if e%2 == 0) yield e
res4: Array[Int] = Array(2, 4)
scala> a
res10: Array[Int] = Array(1, 2, 3, 4, 5)
scala> val b = 6 to 7
b: scala.collection.immutable.Range.Inclusive = Range 6 to 7
scala> for {
| x <-a
| y <-b
| } yield (x,y)
res11: Array[(Int, Int)] = Array((1,6), (1,7), (2,6), (2,7), (3,6), (3,7), (4,6), (4,7), (5,6), (5,7))
scala> for {
| y <- b
| x <- a
| } yield (x,y)
res12: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,6), (2,6), (3,6), (4,6), (5,6), (1,7), (2,7), (3,7), (4,7), (5,7))
for 複雜例項
找出.txt字尾檔案
scala> def getTextFile(path:String) : Array[java.io.File] =
| for {
| file <- new File(path).listFiles
| if file.isFile
| if file.getName.endsWith(".txt")
| } yield file
getTextFile: (path: String)Array[java.io.File]
scala> getTextFile(".")
res9: Array[java.io.File] = Array(./a.txt, ./test.txt)
參考
https://unmi.cc/scala-yield-samples-for-loop/
如非註明轉載, 均為原創. 本站遵循知識共享CC協議,轉載請註明來源