Questions tagged [for-comprehension]

for-comprehension is construction in Scala language allowing easy iteration over one or more collections.

Before we see some examples of for-comprehension lets first define following lists:

val list1 = List("a", "b")
val list2 = List("c", "d")
val list3 = List("e", "f")

Now we can see first example. It is imperative form of for-comprehension. It iterates over each of list and for each combination executes 'println' statement:

for { x <- list1; y <- list2; z <-list3 } println(x+y+z)

The result is:

ace
acf
ade
adf
bce
bcf
bde
bdf

Second example is functional form of for-comprehension. It uses yield keyword to create and return a list:

for { x <- list1; y <- list2; z <-list3 } yield x+y+z

The result is:

List[String] = List(ace, acf, ade, adf, bce, bcf, bde, bdf)
368 questions
97
votes
5 answers

Confused with the for-comprehension to flatMap/Map transformation

I really don't seem to be understanding Map and FlatMap. What I am failing to understand is how a for-comprehension is a sequence of nested calls to map and flatMap. The following example is from Functional Programming in Scala def…
sc_ray
  • 7,803
  • 11
  • 63
  • 100
85
votes
5 answers

Composing Option with List in for-comprehension gives type mismatch depending on order

Why does this construction cause a Type Mismatch error in Scala? for (first <- Some(1); second <- List(1,2,3)) yield (first,second) :6: error: type mismatch; found : List[(Int, Int)] required: Option[?] for (first <- Some(1);…
84
votes
6 answers

withFilter instead of filter

Is it always more performant to use withFilter instead of filter, when afterwards applying functions like map, flatmap etc.? Why are only map, flatmap and foreach supported? (Expected functions like forall/exists as well)
Kigyo
  • 5,668
  • 1
  • 20
  • 24
43
votes
3 answers

Using Eithers with Scala "for" syntax

As I understand it, Scala "for" syntax is extremely similar to Haskell's monadic "do" syntax. In Scala, "for" syntax is often used for Lists and Options. I'd like to use it with Eithers, but the necessary methods are not present in the default…
Dan Burton
  • 53,238
  • 27
  • 117
  • 198
37
votes
5 answers

Future[Option] in Scala for-comprehensions

I have two functions which return Futures. I'm trying to feed a modified result from first function into the other using a for-yield comprehension. This approach works: val schoolFuture = for { ud <- userStore.getUserDetails(user.userId) …
Ryan Bair
  • 2,614
  • 3
  • 18
  • 18
37
votes
4 answers

Is there a way to declare an implicit val inside a for comprehension?

I have some code with nested calls to flatMap like so: foo.flatMap(implicit f => bar(123).flatMap(b => /* and so on... implicit f is still in scope here.*/ )) Normally, one would write that as a for comprehension, which makes the code a lot more…
Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
35
votes
4 answers

Method parameters validation in Scala, with for comprehension and monads

I'm trying to validate the parameters of a method for nullity but i don't find the solution... Can someone tell me how to do? I'm trying something like this: def buildNormalCategory(user: User, parent: Category, name: String, description: String):…
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
32
votes
6 answers

Getting the desugared part of a Scala for/comprehension expression?

Does anyone know how to get the (Scala part only) desugared translation of a for/comprehension expression before it actually tries to compile in the REPL (or compiler)? The only thing I've found so far is the compiler "-print" flag but that gives…
IODEV
  • 1,706
  • 2
  • 17
  • 20
32
votes
4 answers

println in scala for-comprehension

In a for-comprehension, I can't just put a print statement: def prod (m: Int) = { for (a <- 2 to m/(2*3); print (a + " "); b <- (a+1) to m/a; c = (a*b) if (c < m)) yield c } but I can circumvent it easily with a dummy…
user unknown
  • 35,537
  • 11
  • 75
  • 121
26
votes
3 answers

Scala "<-" for comprehension

I have found that Scala always has a "natural explanation" to anything. Always something like "ohh, but that's just a function being called on this and that object with this and that parameter". In a sense, nothing is really compiler-magic as we…
Felix
  • 8,385
  • 10
  • 40
  • 59
25
votes
1 answer

New desugaring behavior in Scala 2.10.1

Suppose I have this monadic class: case class Foo[A](xs: List[A]) { def map[B](f: A => B) = Foo(xs map f) def flatMap[B](f: A => Foo[B]) = Foo(xs flatMap f.andThen(_.xs)) def withFilter(p: A => Boolean) = { println("Filtering!") Foo(xs…
Travis Brown
  • 138,631
  • 12
  • 375
  • 680
24
votes
6 answers

How can I do 'if..else' inside a for-comprehension?

I am asking a very basic question which confused me recently. I want to write a Scala For expression to do something like the following: for (i <- expr1) { if (i.method) { for (j <- i) { if (j.method) { doSomething() }…
Sawyer
  • 15,581
  • 27
  • 88
  • 124
24
votes
4 answers

Scala Future with filter in for comprehension

In the example below I get the exception java.util.NoSuchElementException: Future.filter predicate is not satisfied I want to have the result Future( Test2 ) when the check if( i == 2 ) fails. How do I handle filter/if within a for comprehension…
Magnus
  • 3,691
  • 5
  • 27
  • 35
23
votes
4 answers

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

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 ,…
aioobe
  • 413,195
  • 112
  • 811
  • 826
20
votes
2 answers

What is the idiomatic way to pattern match sequence comprehensions?

val x = for(i <- 1 to 3) yield i x match { case 1 :: rest => ... // compile error } constructor cannot be instantiated to expected type; found : collection.immutable.::[B] required: scala.collection.immutable.IndexedSeq[Int] This is the…
letmaik
  • 3,348
  • 1
  • 36
  • 43
1
2 3
24 25