function - Ocaml 表达式类型混淆
问题描述
我写了这个 ocaml 函数:
(* int Base.List.t -> Base.Int.t x Base.Int.t *)
let min_and_max lst =
let mmax = ref Float.neg_infinity
and mmin = ref Float.infinity in
List.iter ~f:(fun v -> let fv = Float.of_int v in
if fv > !mmax then mmax := fv
else if fv < mmin then mmin := fv)
lst;
(Int.of_float !mmin, Int.of_float !mmax)
它应该返回整数列表的最小值和最大值,但是当我编译时,我得到了这个错误:
File "02-exercises/24-refs/problem.ml", line 25, characters 21-23:
Error: This expression has type Base.Float.t = float
but an expression was expected of type int
错误指向if
该函数中的第一条语句。我一定犯了一个非常明显的错误,但我看不到它。
考虑到到目前为止的答案和评论的解决方案:
let min_and_max lst =
match lst with
| [] -> failwith "Cannot find min and max of empty list"
| v::[] -> (v,v)
| a::b::rest ->
let mmax = ref (max a b)
and mmin = ref (min a b) in
List.iter ~f:(fun v ->
if v > !mmax then mmax := v;
if v < !mmin then mmin := v)
rest;
(!mmin, !mmax)
解决方案
Base 禁用多态比较:您需要使用本地 open 来比较浮点数>
和<
: Float.(fv > !mmax )
。
ps:无偿转换为浮点数(以及引用的使用)有点奇怪且非最佳。
推荐阅读
- git - 从未合并的文件的 git 日志
- c - C字节序和字节数组
- python - 烧瓶运行给我 ModuleNotFoundError
- amazon-web-services - 如何将 S3 存储桶中的文件添加到 AWS CodePipeline 中的输出工件?(NodeJS)
- minecraft - 使用 Spigot 更改盔甲属性
- c# - 事件处理程序通用 C#
- linux - Linux NASM - 隐藏终端输入
- javascript - 如何延迟加载用户脚本的新选项卡?
- nginx - 如何根据 nginx 中的“Content-Length”标头删除额外数据
- drupal - 为什么 Drupal 不能创建临时文件?