如何在 OCaml 中构建文件中字符出现频率的映射?
我想在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的错误非常简单且不言自明。
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 inbuild_freq_map
that actually builds your "map" that you want. So you still have a ways to go.