用F#计算数字列表的笛卡尔积 [英] Calculating the Cartesian product of a list of numbers with F#

查看:83
本文介绍了用F#计算数字列表的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是f#的新手

我试图计算数字列表的笛卡尔积.我借用了"这个.

I am try to calculate the Cartesian products of a list of numbers. I "borrowed" this.

let xs = [1..99]
let ys = [1..99]
seq {for x in xs do for y in ys do yield x * y}

有更好或更优雅的方式吗?

Is there a better or more elegant way?

加里

推荐答案

基于列表模块提供的功能来解决该问题的另一种可能性是:

Another possibiltiy to tackle the problem based on functionality provided by the List module would be:

let xs = [1..99]
let ys = [1..99]
let zs = xs |> List.collect (fun x -> ys |> List.map (fun y -> x*y))

避免了对.concat的额外调用,并且应该也可以完成工作.

which avoids the extra calls to .concat and should also do the job.

但是我会坚持使用您的解决方案.它应该是最易读的,才是真正的比赛赢家. (只需尝试大声朗读代码即可.您的代码完全可以理解,而Noldorins或我的代码则无法理解.)

But I'd stick with your solution. It should be the most readable which is a real matchwinner. (Just try to read the codes out loud. Yours is perfectly understandable and Noldorins or mine are not.)

这篇关于用F#计算数字列表的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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