OCaml中的组功能

时间:2014-03-01 21:45:48

标签: ocaml

我正在研究一个问题,我根据使用高阶函数的谓词将列表分组为大量列表。

val group: ('a -> 'a -> bool) -> 'a list -> 'a list list

例如,

示例1:

# group sameLength ["phone", "iron", "man", "mouse", "ice"];;

-: string list list = 

[["iron"; "ice"] ; ["man"; "mouse"]; ["phone"]]

示例2:

# group (sameMod 2) [-5; -4; -3; -2; -1; 0; 1; 2; 3; 4; 5];;

-: int list list = [[-4; -2; 0; 2; 4]; [-5; -3; -1; 1; 3; 5]]

这就是我现在所拥有的但是行为不正确

let group p = List.fold_right (fun x (tlst, flst) -> if p x then (x:: tlst) else (tlst, x::flst)) tlst List.@ (group p flst)

(* trying to output tlst based on predicate and append onto group function (flst) *)

有没有人有任何分享指针?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

首先,我们需要注意,如果f x y = truef x z = true然后f y z = true

所以我们能做的就是

  1. 从列表中获取元素x
  2. 然后将列表分为l1l2。在l1中,f x的所有元素都是truel2中的所有元素都是falsex
  3. 继续分组l2
  4. 当所有元素彼此O(N^2)时,最差情况时间复杂度为false


    let group f l =
      let rec grouping acc = function
        | [] -> acc
        | hd::tl ->
          let l1,l2 = List.partition (f hd) tl in
          grouping ((hd::l1)::acc) l2
      in 
      grouping [] l
    
    let same_len s1 s2 = String.length s1 = String.length s2
    
    let same_mod m x y = x mod m = y mod m
    
    let l = ["phone";"iron";"man";"mouse";"ice"]
    
    # group same_len l;;
    - : string list list = [["man"; "ice"]; ["iron"]; ["phone"; "mouse"]]