KChaloux KChaloux -3 years ago 199
Scala Question

Composing a list of all pairs

I'm brand new to Scala, having had very limited experience with functional programming through Haskell.

I'd like to try composing a list of all possible pairs constructed from a single input list. Example:

val nums = List[Int](1, 2, 3, 4, 5) // Create an input list
val pairs = composePairs(nums) // Function I'd like to create

// pairs == List[Int, Int]((1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1) ... etc)

I tried using
on each element with the whole list, hoping that it would duplicate the one item across the whole. It didn't work (only matched the first possible pair). I'm not sure how to repeat an element (Haskell does it with
I believe), and I've had trouble following the documentation on Scala.

This leaves me thinking that there's probably a more concise, functional way to get the results I want. Does anybody have a good solution?

Answer Source

How about this:

val pairs = for(x <- nums; y <- nums) yield (x, y)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download