Skip to content

Instantly share code, notes, and snippets.

@mads-hartmann
Created September 23, 2011 08:17
Show Gist options
  • Save mads-hartmann/1236950 to your computer and use it in GitHub Desktop.
Save mads-hartmann/1236950 to your computer and use it in GitHub Desktop.
More statements in the for-comprehension wanted
val op1 = Some("test")
val op2 = Some("test")
val l1 = List(1,2,3)
val l2 = List(1,2,3)
val product: Option[List[(Int,Int)]] = for {
t1 <- op1
t2 <- op2
} yield l1.flatMap { l => l2.map { l2 => (l,l2) }}
/*
It is my understanding that for-comprehensions are just
syntactic sugar for flatMap/filer so if I can write the
following it should be able to do as for-comprehension. Right?
*/
op1.flatMap { t1 =>
op2.flatMap { t2 => Some(
l1.flatMap { l =>
l2.flatMap { l2 =>
List((l,l2))
}})}}
@teigen
Copy link

teigen commented Sep 23, 2011

val op1 = Some("test")
val op2 = Some("test")
val l1 = List(1,2,3)
val l2 = List(1,2,3)

val product: Option[List[(Int,Int)]] = for {
  t1 <- op1
  t2 <- op2 
} yield l1.flatMap { l => l2.map { l2 => (l,l2) }}

/*
  It is my understanding that for-comprehensions are just
  syntactic sugar for flatMap/filer so if I can write the
  following it should be able to do as for-comprehension. Right? 
*/

val r = op1.flatMap { t1 => 
op2.flatMap { t2 => Some(
l1.flatMap  { l  => 
l2.flatMap  { l2 => 
  List((l,l2))
}})}}

/* what you wrote as a for comprehension*/
val r2 = for {
  t1 <- op1
  t2 <- op2
  x <- Some(l1.flatMap{ l => l2.flatMap{ l2 => List((l, l2)) }})
} yield x

/* which can be simplified to */
val r3 = for {
  t1 <- op1
  t2 <- op2
  x = l1.flatMap{ l => l2.map{ l2 => (l, l2) }}
} yield x

/* or by using another for comprehension */
val r4 = for {
  t1 <- op1
  t2 <- op2
  x = for{
    l <- l1
    l2 <- l2
  } yield (l, l2)
} yield x

/* and dropping the x variable and just doing the second for in the yield block directly */
val r5 = for{
  _ <- op1
  _ <- op2
} yield for {
  l <- l1
  l2 <- l2
} yield (l, l2)

println(r)
println(r2)
println(r3)
println(r4)
println(r5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment