两个列表的叉积 [英] Cross product of two lists

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

问题描述

处理 List 模块的扩展函数".(我花了很长时间开发mapfold"——它线程像折叠这样的累加器,但使用它作为参数来创建像 map 这样的新值——然后发现这就是 List.scan_left 所做的)

为了生成测试数据,我需要做两个列表的叉积,这是我想出的:

For generation of test data, I needed to do a cross product of two lists, This is what I came up with:

///Perform cross product of two lists, return tuple
let crossproduct l1 l2 =
    let product lst v2 = List.map (fun v1 -> (v1, v2)) lst
    List.map_concat (product l1) l2

这有什么好处,还是已经有更好的方法来做到这一点?

Is this any good, or is there already some better way to do this?

同样的问题:

///Perform cross product of three lists, return tuple
let crossproduct3 l1 l2 l3 =
    let tuplelist = crossproduct l1 l2 //not sure this is the best way...
    let product3 lst2 v3 = List.map (fun (v1, v2) -> (v1, v2, v3)) lst2
    List.map_concat (product3 tuplelist) l3

推荐答案

另一种选择是使用 F#序列表达式"并编写如下内容:

another option is to use F# "sequence expressions" and write something like this:

let crossproduct l1 l2 =
  seq { for el1 in l1 do
          for el2 in l2 do
            yield el1, el2 };;

(其实和你写的差不多,因为'for .. in .. do' in sequence expression 可以看成是map_concat).这适用于(惰性)序列,但如果您想使用列表,您只需将代码包装在 [ ... ] 中,而不是在 seq { ... } 中.

(actually, it is almost the same thing as what you wrote, because 'for .. in .. do' in sequence expression can be viewed as map_concat). This works with (lazy) sequences, but if you want to work with lists, you'd just wrap the code inside [ ... ] rather than inside seq { ... }.

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

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