实现二进制搜索时键入错误

时间:2014-12-16 23:13:20

标签: ocaml

我有以下代码:

open Array

let binSearch a x =
    let l = ref 0 in
    let r = ref (length a) in
    let m = ref 0 in
    while l < r do
        !m := (!l + !r) / 2; (*line 8*)
        if (a.(!m) = x) then
        begin
            !r := !m;
            !l := !r
        end
        else if (a.(!m) > x) then
            !p := !m
        else
            !l := !m + 1
    done;
    a.(!l) = x
;;

当我尝试编译它时,我收到以下错误:

File "binSearch.ml", line 8, characters 2-4:
Error: This expression has type int but an expression was expected of type
     'a ref

为什么编译器期望'a ref

1 个答案:

答案 0 :(得分:2)

您无需将!放在:=运算符的左侧。运营商:=的类型为'a ref -> 'a -> unit,换句话说,左侧应为'a,右侧应为'a。所以,而不是:

 !r := !m (* WRONG *)

你需要

 r := !m