Dunno
Dunno

Reputation: 3684

Type error when implementing binary search

I have the following code:

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
;;

when I try to compile it I get the following error:

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

Why is the compiler expecting 'a ref?

Upvotes: 1

Views: 60

Answers (1)

ivg
ivg

Reputation: 35280

You do not need to put ! on the left side of the := operator. Operator := has type 'a ref -> 'a -> unit, in other words there should be a reference to 'a at the left side and 'a at the right side. So, instead of:

 !r := !m (* WRONG *)

you need

 r := !m

Upvotes: 2

Related Questions