Skip to content

Instantly share code, notes, and snippets.

@squito
Last active December 28, 2015 20:18
Show Gist options
  • Save squito/7555885 to your computer and use it in GitHub Desktop.
Save squito/7555885 to your computer and use it in GitHub Desktop.
find first match in scala nested for loops
val data = (1 to 10).toSeq.map{i => (0 to i).map{_.toString}.toSeq}
val iters = for {
sub <- data.iterator
d <- sub.iterator
} yield d
val r = iters.find{x =>
println(s"checking $x")
x == "6"
}
//of course, no need for tmp var
(for {
sub <- data.iterator
d <- sub.iterator
} yield d).find{x => println(s"checking $x"); x == "6"}
//outputs:
checking 0
checking 1
checking 0
checking 1
checking 2
checking 0
checking 1
checking 2
checking 3
checking 0
checking 1
checking 2
checking 3
checking 4
checking 0
checking 1
checking 2
checking 3
checking 4
checking 5
checking 0
checking 1
checking 2
checking 3
checking 4
checking 5
checking 6
r: Option[String] = Some(6)
(for {
sub <- data.iterator
d <- sub.iterator
} yield d).find{x => println(s"checking $x"); x == "6"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment