List all pairs

I am new to Scala with very limited experience with functional programming through Haskell.

I would like to try to make a list of all possible pairs built from one 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 zip for each item with the whole list, hoping that it would duplicate one item throughout. This did not work (only coincided with the first possible pair). I'm not sure how to repeat the element (Haskell does this with cycle and take , I reckon), and I am having problems with the Scala documentation.

This makes me think that there may be a more concise, functional way to get the results I want. Anyone have a good solution?

+7
source share
3 answers

How about this:

 val pairs = for(x <- nums; y <- nums) yield (x, y) 
+20
source

For those of you who don't want to duplicate:

 val uniquePairs = for { (x, idxX) <- nums.zipWithIndex (y, idxY) <- nums.zipWithIndex if idxX < idxY } yield (x, y) val nums = List(1,2,3,4,5) uniquePairs: List[(Int, Int)] = List((1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)) 
+2
source

Here is another version using map and flatten

val pairs = nums.flatMap(x => nums.map(y => (x,y)))

List[(Int, Int)] = List((1,1), (1,2), (1,3), (1,4), (1,5), (2,1), (2,2), (2,3), (2,4), (2,5), (3,1), (3,2), (3,3), (3,4), (3,5), (4,1), (4,2), (4,3), (4,4), (4,5), (5,1), (5,2) (5,3), (5,4), (5,5))

Then it can be easily included in the composePairs function if you want:

 def composePairs(nums: Seq[Int]) = nums.flatMap(x => nums.map(y => (x,y))) 
+1
source

All Articles