OCAML将此代码从组合更改为排列

时间:2015-04-28 05:55:02

标签: ocaml combinations permutation

这是获取int和列表的代码,在给定不同对象的数量的情况下制作该列表的所有可能组合。例如,如果你插入int 2作为列表[1; 2;它给你[1; 2],[2; 3],[1; 3]!我想要它做的是给我排列而不是组合顺序重要!如何更改此代码才能为我执行此操作?

# let extract k list =
  let rec aux k acc emit = function
  | [] -> acc
  | h :: t ->
    if k = 1 then aux k (emit [h] acc) emit t else
      let new_emit x = emit (h :: x) in
      aux k (aux (k-1) acc new_emit t) emit t
  in
  let emit x acc = x :: acc in
  aux k [] emit list;;

val extract : int -> 'a list -> 'a list list = <fun>
# 

1 个答案:

答案 0 :(得分:0)

此代码相当棘手,因为它依赖于重新定义emit函数以向发出的列表添加前缀。我想你可以直接写一下这个函数。

尽管如此,尝试一件事可能是让new_emit(修改后的emit)添加h不仅仅是作为前缀而是列在列表中的每个可能位置x。我没试过这个,但听起来不错。