Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

scala - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...