编写所有对的列表 [英] Composing a list of all pairs

查看:103
本文介绍了编写所有对的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Scala的全新人物,通过Haskell进行函数式编程的经验非常有限。

我想尝试编写一个由单个输入列表构成的所有可能对的列表。示例:

  val nums = List [Int](1,2,3,4,5)//创建输入列表
val pairs = composePairs(nums)//函数我想创建

//对==列表[Int,Int]((1,1),(1,2 ),(1,3),(1,4),(1,5),(2,1)...等)

我试着在整个列表的每个元素上使用 zip ,希望它能在整个列表中复制一个项目。它没有工作(只匹配第一个可能的对)。我不确定如何重复一个元素(Haskell通过 cycle take 我相信)来执行它,而I在遵循Scala的文档方面遇到了麻烦。

这让我想到可能有更简洁,更实用的方法来获得我想要的结果。有没有人有一个很好的解决方案?

解决方案

这样的情况如何:

<$ (x < - nums; y < - nums)yield(x,y)


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?

解决方案

How about this:

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

这篇关于编写所有对的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆