【发布时间】:2015-11-22 23:53:29
【问题描述】:
let rec n_cartesian_product = function
| [] -> [[]]
| x :: xs ->
let rest = n_cartesian_product xs
List.concat (List.map (fun i -> List.map (fun rs -> i :: rs) rest) x)
你好!我写了这个函数,但我需要在不使用任何List.* 内置函数的情况下编写它。由于有一个调用外部函数的内部函数,我假设我必须定义两个相互递归的函数。
定义一个 concat 函数似乎很容易:
let rec list_concat ( lst : 'a list list ) : 'a list =
match lst with
[] -> []
|x::xs -> x @ (list_concat xs)
问题是,我被困在产生 concat 参数的函数的定义上:
let rec fun_i rest =
match rest with
[] -> []
|x::xs -> fun_rs
and fun_rs =
fun_i :: fun_rs
我似乎无法设计出合适的解决方案。你能帮帮我吗?
编辑:例如,给定这个输入
[["A";"a"];["B";"b"];["C";"c"]]
我想要这个输出:
[["A"; "B"; "C"]; ["A"; "B"; "c"]; ["A"; "b"; "C"]; ["A"; "b"; "c"];
["a"; "B"; "C"]; ["a"; "B"; "c"]; ["a"; "b"; "C"]; ["a"; "b"; "c"]]
【问题讨论】:
-
简单的答案 - concat 和 map 可在源代码中使用递归定义
-
在哪里可以找到它们的来源?谢谢。
-
干杯,约翰·帕默!
标签: function recursion f# mutual-recursion