【问题标题】:merge (int * string) list ocaml合并 (int * string) 列表 ocaml
【发布时间】:2013-11-24 18:15:32
【问题描述】:

我有这个功能:

let encode list =
let rec aux count acc = function
 | [] -> [] (* Caso a lista esteja vazia*)
 | [x] -> (count+1, x) :: acc
 | a :: (b :: _ as t) -> 
    if a = b then aux (count + 1) acc t
            else aux 0 ((count+1,a) :: acc) t in
        List.rev (aux 0 [] list)
;;

并使用此输入:

let test = encode ["a";"a";"a";"a";"b";"f";"f";"c";"c";"a";"a";"d";"e";"e";"e";"e"];;

我有这个输出:

val test : (int * string) list =
[(4, "a"); (1, "b"); (2, "f"); (2, "c"); (2, "a"); (1, "d"); (4, "e")]

但是“a”是重复的,“f”需要在最后! 我需要这样的输出:

val test : (int * string) list =
[(6, "a"); (1, "b"); (2, "c"); (1, "d"); (4, "e"); (2, "f")]

有人可以帮忙吗?!谢谢!

【问题讨论】:

    标签: list function count char ocaml


    【解决方案1】:

    您正在计算重复的相邻值,即所谓的游程编码。看来您想计算整个输入中的出现次数。您可以预先对输入进行排序,也可以使用更复杂的数据结构(例如 Map)来跟踪计数。

    【讨论】:

      【解决方案2】:

      类似这样的:

      let encode xs = 
        let f acc x = 
          let n = try M.find x acc  with Not_found -> 0 in 
          M.add x (n+1) acc in
        let ans = (List.fold_left f M.empty) xs in 
        M.bindings ans ;;
      
      # encode ["a";"a";"a";"a";"b";"f";"f";"c";"c";"a";"a";"d";"e";"e";"e";"e"];;
      - : (M.key * int) list =
      [("a", 6); ("b", 1); ("c", 2); ("d", 1); ("e", 4); ("f", 2)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多