1

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
  }
1
  • Use yield. Also, you can use two generators in one for statement. Commented Apr 27, 2014 at 21:49

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.