开发者

How to build a map of the frequency with which characters occur in a file in OCaml?

I would like to create a function in OCaml that returns a map of how often each character occurs in a file. For example, consider a file containing this:

AAAAA BB C

That input would produce this map:

{ ' ' -> 2, 'A' -> 5, 'B' -> 2, 'C' -> 1 }

Here's what I have so far:

let usage = "usage: " ^ Sys.argv.(0) ^ " [OPTION]... [FILE]..."
let file = ref ""
let speclist = [
  ("-z", Arg.String (fun c -> file := c), " compress [FILE]");
  ("-d", Arg.String (fun d -> file := d), " decompress [FILE]");
]

let build_freq_map f =
  let channel = open_in f in
  function x ->
    input_byte channel

let () =
  Arg.parse
    speclist
    (fun x -> raise (Arg.Bad ("Bad argument: " ^ x)))
    usage;

  build_freq_map !file;

But this doesn't compile开发者_如何学Python, saying:

File "main.ml", line 19, characters 1-22:
Error: This expression has type 'a -> int
       but an expression was expected of type unit

How would I modify my code so that build_frequency_map returns a map of a file's characters and frequencies?


Your error is pretty simple and self-explanatory. build_freq_map !file has a function type (it returns a function). You are pattern matching that whole thing with () i.e. the unit type. So the types don't match.

It looks like your program is kinda incomplete, because it doesn't output anything or do anything with the result it gets from build_freq_map. Furthermore, I don't see any logic in build_freq_map that actually builds your "map" that you want. So you still have a ways to go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜