如何在 OCaml 中构建文件中字符出现频率的映射?

发布于 2024-12-08 08:38:14 字数 941 浏览 1 评论 0原文

我想在 OCaml 中创建一个函数,它返回每个字符在文件中出现频率的映射。例如,考虑一个包含以下内容的文件:

AAAAA BB C

该输入将生成此映射:

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

这是迄今为止我所拥有的:

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;

但这无法编译,说:

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

我将如何修改我的代码,以便 build_Frequency_map 返回文件字符和频率的映射?

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, 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

究竟谁懂我的在乎 2024-12-15 08:38:14

您的错误非常简单且不言自明。 build_freq_map !file 有一个函数类型(它返回一个函数)。您正在将整个事物与 () 进行模式匹配,即单位类型。所以类型不匹配。

看起来您的程序有点不完整,因为它没有输出任何内容,也没有对从 build_freq_map 获得的结果执行任何操作。此外,我在 build_freq_map 中没有看到任何实际构建您想要的“地图”的逻辑。所以你还有很长的路要走。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文