如何只在F#中使用递归来编写这个函数?

时间:2015-11-22 23:53:29

标签: function recursion f# mutual-recursion

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"]]

1 个答案:

答案 0 :(得分:2)

N-Cartesian产品

要递归地定义n笛卡尔积,最简单的方法就是对原始(非递归)示例中使用的函数进行递归定义:

let rec list_concat lst =
    match lst with 
    |[]    -> []
    |x::xs  -> x @ (list_concat xs)

let rec list_map f lst =
    match lst with
    |[] -> []
    |x::xs -> (f x) :: list_map f xs

let rec n_cartesian_product = 
    function
    | [] -> [[]]
    | x :: xs ->
      let rest = n_cartesian_product xs 
      list_concat (list_map (fun head -> list_map (fun tail -> head :: tail) rest) x)

在F#中以惯用方式编写时,最好使用更多通用函数(如fold)编写,而不是使用显式递归创建大量自定义函数。因此,您可以定义一些其他功能:

let list_collect f = list_concat << list_map f

let rec list_fold f acc lst =
    match lst with
    |[] -> acc
    |hd::tl -> list_fold f (f acc hd) tl

let n_cartesian_product_folder rest first = 
    list_collect (fun head -> list_map (fun tail -> head :: tail) rest) first

然后我们可以简单地将n_cartesian_product重新定义为:

let n_cartesian_product2 lst = list_fold (n_cartesian_product_folder) [[]] lst

如果我们使用F#核心库函数(而不是自定义递归实现),这种方法将涉及更多标准代码,而不会出错。

笛卡尔积 (我会把这部分留在这里,因为它显然很有用)

定义一个获取'a列表的函数,并列出'b * 'a列表,其中'b类型的所有内容都是一些提供的元素y

/// take a list of 'a and make a list of (y, 'a)
let rec tuplify y lst =
    match lst with
    |[] -> []
    |x::xs -> (y, x) :: (tuplify y xs)

然后定义一个函数,通过我的列表进行递归,在第一个列表的当前元素和整个第二个列表上调用tuplify,并通过递归调用笛卡尔积来连接它。

/// cartesian product of two lists
let rec cartesianProduct lst1 lst2 =
    match lst1 with
    |[] -> []
    |x::xs -> tuplify x lst2 @ (cartesianProduct xs lst2)