Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 合并(int*string)列表ocaml_List_Function_Count_Char_Ocaml - Fatal编程技术网

List 合并(int*string)列表ocaml

List 合并(int*string)列表ocaml,list,function,count,char,ocaml,List,Function,Count,Char,Ocaml,我有这个功能: 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)

我有这个功能:

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

有人能帮忙吗?!谢谢

您正在计算重复的相邻值,即所谓的运行长度编码。似乎您希望计算整个输入中的出现次数。您可以事先对输入进行排序,也可以使用更复杂的数据结构(如地图)来跟踪计数。

类似以下内容:

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