乱用List模块的"扩展功能".(我花了很长时间开发'mapfold' - 它将一个累加器像fold折叠,但是使用它作为参数来创建像map这样的新值 - 然后发现那是什么List.scan_left)
为了生成测试数据,我需要做两个列表的交叉产品,这就是我提出的:
///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
Run Code Online (Sandbox Code Playgroud)
这有什么好处,还是有更好的方法来做到这一点?
同样的问题:
///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 …Run Code Online (Sandbox Code Playgroud) 我被给了一个谜题作为礼物.它由4个立方体组成,并排排列.每个立方体的面是四种颜色之一.
为了解决难题,立方体必须定向,以便所有四个立方体的顶部不同,它们的所有前沿都不同,它们的背部都是不同的,并且它们的底部都是不同的.左右两边无所谓.
我的伪代码解决方案是:
我使用F#中的伪代码实现解决了这个难题,但我对第3步的处理方式并不满意:
let problemSpace =
seq { for c1 in cube1Orientations do
for c2 in cube2Orientations do
for c3 in cube3Orientations do
for c4 in cube4Orientations do
yield [c1; c2; c3; c4] }
Run Code Online (Sandbox Code Playgroud)
上面的代码非常具体,只能得出四个方向序列的笛卡尔积.我开始考虑为n个方向序列编写它的方法.
我提出了(从现在开始的所有代码应该在F#interactive中执行得很好):
// Used to just print the contents of a list.
let print =
Seq.fold (fun s i -> s + i.ToString()) "" >> printfn "%s"
// Computes the product of two sequences - kind of; the 2nd argument is …Run Code Online (Sandbox Code Playgroud) 我来自SML背景,对高阶函数感觉很舒服.但我真的不明白列表理解.是否存在列表理解比高阶函数更合适的情况,List反之亦然?
我听说列表理解比高阶函数慢,我应该避免在编写性能关键函数时使用它吗?
为了示例,请查看在F#中有效地投影列表列表,其中@cfern的答案分别包含使用列表推导和高阶函数的两个版本:
let rec cartesian = function
| [] -> [[]]
| L::Ls -> [for C in cartesian Ls do yield! [for x in L do yield x::C]]
Run Code Online (Sandbox Code Playgroud)
和:
let rec cartesian2 = function
| [] -> [[]]
| L::Ls -> cartesian2 Ls |> List.collect (fun C -> L |> List.map (fun x->x::C))
Run Code Online (Sandbox Code Playgroud) 我是f#的新手
我试着计算一组数字的笛卡尔积.我"借"了这个.
let xs = [1..99]
let ys = [1..99]
seq {for x in xs do for y in ys do yield x * y}
Run Code Online (Sandbox Code Playgroud)
有更好或更优雅的方式吗?
加里
可能重复:
F# - 两个列表的交叉乘积
在F#中有效地投影列表列表
我有一个函数,它接受两个整数列表,并返回一个包含所有笛卡儿积的列表.我认为我有正确的想法,但没有正确的实施.我可以得到一些指示吗?
let rec cartesian = function
| ([],[]) -> []
| (xs,[]) -> []
| ([],ys) -> []
| (x::xs,ys) -> List.map(fun y -> (x,y)::[]) cartesian (xs,ys)
Run Code Online (Sandbox Code Playgroud)