1

我正在尝试编写一个在给定列表的每个位置插入整数 n 的函数。小例子,insert_everywhere 0 [1;2] -> [[0;1;2]; [1;0;2]; [1;2;0]]。我写了这个:

let insert_everywhere l n  = 
  let l_aux = [] in 
  let rec aux l1 l2 = match l1 with
    | [] -> []
    | x::tl -> (l_aux @ [n] @ l1) :: aux tl (l_aux @ [x])
  in aux l l_aux
;;

问题是调用aux tl (l_aux @ [x])不符合我的要求。我的想法是:当我阅读列表的头部时,我插入另一个列表,我将其附加到数字n和列表的其余部分。通过这种方式,我将获得最终列表,但我目前的实现却没有……</p>

4

1 回答 1

0

好吧,解决方案与名为zipper. 如果第一个参数是列表的第一个参数,则您需要保留未评估的列表尾部,aux并且还需要保留列表的评估前缀以构建它的一部分答案。您不需要l_aux,我们将使用第二个参数而不是使用可变变量。让我们看看骨架

let insert_everywhere l (n : int)  =
  let rec aux l1 l2 : int list list = match l1 with
  | [] ->  (* There we need to built a part of answer 
              from l1 prefix, n and empty tail postfix*)
  | x::tl -> (* There we need to construct part of answer *) 
             :: aux tl ( (* construct new prefix from old one and `n` there *) )
  in
  aux l []

如果您仍然找不到答案,您可以在那里查看我的解决方案。当您找到答案时,我会将其添加到我的答案中。尽量不要偷看链接!:)

附言

let insert_everywhere l (n : int)  =
  let rec aux l1 l2 = match l1 with
  | [] -> [l2 @ [n]]
  | x::tl -> (l2 @ [n] @ l1) :: aux tl (l2 @ [x])
  in
  aux l []
于 2013-11-07T20:53:16.630 回答