blue-sky
blue-sky

Reputation: 53806

Returning values from an inner loop in Scala, use a function instead?

I'm attempting to return a value from a inner loop. I could create a outside list and populate it within the inner loop as suggested in comments below but this does not feel very functional. Is there a function I can use to achieve this ?

The type of the loop/inner loop is currently Unit but I would like it to be of type List[Int] or some similar collection type.

 val data = List(Seq(1, 2, 3, 4), Seq(1, 2, 3, 4))

//val list : List   
  for(d <- data){
    for(d1 <- data){
      //add the result to the val list defined above
      distance(d , d1)
    }
  }

  def distance(s1 : Seq[Int], s2 : Seq[Int]) = {
    s1.zip(s2).map(t => t._1 + t._2).sum
  }

Upvotes: 1

Views: 272

Answers (1)

Erik Kaplun
Erik Kaplun

Reputation: 38217

val list = for (x <- data; y <- data) yield distance(x, y)

will do what you want, yielding:

List(20, 20, 20, 20)

The above desugared is equivalent to:

data.flatMap { x => data.map { y => distance(x, y) } }

The trick is to not nest for-comprehensions because that way you'll only ever get nested collections; to get a flat collection from a conceptually nested iteration, you need to make sure flatMap gets used.

Upvotes: 2

Related Questions