1 ocaml
我正在学习ocaml,所以这可能是微不足道的.
当我尝试构建此代码的可执行文件时:
open Core.Std
let build_counts () =
  In_channel.fold_lines stdin ~init:[] ~f:(fun counts line ->
    let count =
      match List.Assoc.find counts line with
      | None -> 0
      | Some x -> x
    in
    List.Assoc.add counts line (count + 1)
  )
let () =
  build_counts ()
  |> List.sort ~cmp:(fun (_,x) (_,y) -> Int.descending x y)
  |> (fun l -> List.take l 10)
  |> List.iter ~f:(fun (line,count) -> printf "%3d: %s\n" count line)
我收到此错误:
错误:此模式匹配类型'a选项的值,但是期望的模式匹配类型等于的值:(Stdio __.Import.string - > Stdio __.Import.string - > bool) - >'b选项
问题出在哪儿?
链接:https://realworldocaml.org/v1/en/html/files-modules-and-programs.html
以下是类型签名List.Assoc.find:
('a, 'b) Base__List.Assoc.t -> equal:('a -> 'a -> bool) -> 'a -> 'b option
第一个参数是关联列表(counts在示例中).最后一个参数(类型'a)是您要查找的键(line在您的示例中).然而,另一个论点是'a -> 'a -> bool标记的类型equal.它非常简单,它是一个比较函数,用于List.Assoc.find查看两个键是否相等.
在该情况下'a是string,简单的(=)就足够了.您可以通过match使用以下内容替换您的行来修复代码:
match List.Assoc.find counts ~equal:(=) line with
该List.Assoc.add功能遵循相同的模式.您应该build_counts使用以下内容替换函数的最后一行:
List.Assoc.add counts ~equal:(=) line (count + 1)
作为旁注,Real World OCaml已经相当陈旧(这就是为什么有些例子已经过时),作者正在研究第二版.
| 归档时间: | 
 | 
| 查看次数: | 236 次 | 
| 最近记录: |