首页 > 解决方案 > 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)

标签: functiontuplesocaml

解决方案


Base 禁用多态比较:您需要使用本地 open 来比较浮点数><: Float.(fv > !mmax )

ps:无偿转换为浮点数(以及引用的使用)有点奇怪且非最佳。


推荐阅读