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

查看:19
本文介绍了使用 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?

加里

推荐答案

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

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.

但我会坚持你的解决方案.它应该是最易读的,这是真正的比赛赢家.(试着大声朗读代码.你的完全可以理解,而诺多灵或我的则不是.)

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天全站免登陆