我是 OCaml 的初学者,我想从文件中读取行,然后检查每行中的所有字符。作为一个虚拟示例,假设我们要计算文件中字符“A”的出现次数。
我尝试了以下
open Core.Std
let count_a acc string =
let rec count_help res stream =
match Stream.peek stream with
| None -> res
| Some char -> Stream.junk stream; if char = 'A' then count_help (res+1) stream else count_help res stream
in acc + count_help 0 (Stream.of_string string)
let count_a = In_channel.fold_lines stdin ~init:0 ~f:count_a
let () = print_string ((string_of_int count_a)^"\n"
我用它编译
ocamlfind ocamlc -linkpkg -thread -package core -o solution solution.ml
运行它
$./solution < huge_file.txt
在一个有一百万行的文件上,这给了我以下时间
real 0m16.337s
user 0m16.302s
sys 0m0.027s
这是我的python实现的4倍。我很确定应该可以让它更快,但我应该怎么做呢?