【发布时间】:2021-02-05 00:11:44
【问题描述】:
我有一个方法可以返回列表中最常见元素的计数(特别是 char 值列表)
这是我的代码:
let getMostFrequentCharCount li =
let hashTable = Hashtbl.create (List.length li)
in
let rec getMostFrequentCharCount li acc =
match li with
[] -> acc
| head::tail ->
(match (Hashtbl.find hashTable head) with
exception Not_found -> Hashtbl.add hashTable head 1
| _ -> let currentFreq = Hashtbl.find hashTable head
in
Hashtbl.replace hashTable head (currentFreq+1));
let currentFreq = Hashtbl.find hashTable head
in
if currentFreq > acc
then
getMostFrequentCharCount tail currentFreq
else
getMostFrequentCharCount tail acc
in
getMostFrequentCharCount li 0;;
由于某种原因,当我删除第二个模式匹配块(以 match (Hashtbl.find hashTable head) with 开头)周围的括号时,我的编译器抱怨我的累加器 acc 在下一个 if 语句 if currentFreq > acc 中有类型单元,而 @987654325 @ 应该有 int 类型。
为什么括号修复了这个错误?
【问题讨论】:
标签: ocaml