Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

* Scripting Languages
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* aktuális (2023/24/2)
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

for comprehension

#############################

It is similar to Python's list comprehensions.

scala> for (i <- 1 to 10) yield 2 * i
res7: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

After a yield you provide an expression. However, the value of a block is also an expression, thus you can create more complex comprehensions. For instance, uppercase every 2nd letter of a string:

scala> val s = "scala"
s: String = scala

scala> for (i <- s.indices) yield {
     | if (i % 2 == 0) s(i).toString.toUpperCase    // s(i) is a Char, and a Char has no toUpperCase method
     | else s(i).toString                           // let all elements in the result be strings
     | }
res11: scala.collection.immutable.IndexedSeq[String] = Vector(S, c, A, l, A)

Transforming an Array / ArrayBuffer / etc.

scala> val a = Array(20, 5, 4)
a: Array[Int] = Array(20, 5, 4)

scala> val res = for (e <- a) yield 2 * e
res: Array[Int] = Array(40, 10, 8)

The for comprehension creates a new collection whose type is the same as the original collection's type (that you iterate over).

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2015 March 15, 09:52