创建直方图OCaml [英] create a histogram OCaml

查看:83
本文介绍了创建直方图OCaml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是创建一个直方图,以输出元素在列表中的次数.

My task is to create a histogram that output the number of times that an element it is in a list.

Input:[2;2;2;3;4;4;1]
Output[(2, 3); (2, 2); (2, 1); (3, 1); (4, 2); (4, 1); (1, 1)]  
Expected output : [(2, 3); (3, 1); (4, 2); (1, 1)]

My code:

let rec count a ls = match ls with
  |[]              -> 0
  |x::xs  when x=a -> 1 + count a xs
  |_::xs           -> count a xs

let rec count a = function
  |[]              -> 0
  |x::xs  when x=a -> 1 + count a xs
  |_::xs           -> count a xs

let rec histo l = match l with
|[] -> []
|x :: xs ->  [(x, count x l)] @ histo xs ;;

我做错了什么?

推荐答案

问题是xs包含等于x的潜在元素.这是您在输出中看到的结果:(2,3)表示列表中有3乘2.那么xs等于[2; 2; 3; 4; 4; 1] ...等等.

The issue is that xs contains potentially elements that are equal to x. This is what you see in your ouput : (2,3) means that there is 3 times 2 in the list; xs is then equals to [2;2;3;4;4;1]... and so on.

也(不影响结论):您有2个count的定义,但它们是相同的.

Also (not impacting the conclusion): you have 2 definitions of count, but they are identical.

要实现直方图,请使用Hashtbl:

To implement an histogram, use Hashtbl :

let h = Hashtbl.create 1000;;    
List.iter (fun x -> let c = try Hashtbl.find h x with Not_found -> 0 in Hashtbl.replace h x (c+1)) your_list;;
Hashtbl.fold (fun x y acc ->  (x,y)::acc) h [];;

这篇关于创建直方图OCaml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆