Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 zip 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 cycle and take 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?

like image 298
KChaloux Avatar asked Aug 03 '12 21:08

KChaloux


1 Answers

How about this:

val pairs = for(x <- nums; y <- nums) yield (x, y)
like image 170
dbyrne Avatar answered Oct 02 '22 16:10

dbyrne