乱用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) 我必须对列表列表进行投影,这些列表返回每个列表中每个元素的所有组合.例如:
projection([[1]; [2; 3]]) = [[1; 2]; [1; 3]].
projection([[1]; [2; 3]; [4; 5]]) = [[1; 2; 4]; [1; 2; 5]; [1; 3; 4]; [1; 3; 5]].
Run Code Online (Sandbox Code Playgroud)
我想出了一个功能:
let projection lss0 =
let rec projectionUtil lss accs =
match lss with
| [] -> accs
| ls::lss' -> projectionUtil lss' (List.fold (fun accs' l ->
accs' @ List.map (fun acc -> acc @ [l]) accs)
[] ls)
match lss0 with
| [] -> []
| ls::lss' ->
projectionUtil lss' (List.map …Run Code Online (Sandbox Code Playgroud) 我想写这样的东西
[(x,y)|x<- [1,2,3], y <- [’a’,’b’]]
=> [(1,’a’),(1,’b’),(2,’a’),(2,’b’),(3,’a’),(3,’b’)]
Run Code Online (Sandbox Code Playgroud)