s1t2
s1t2

Reputation: 3

Ocaml - unexpected output

I have following code presented below:

let str = "AA";;
let i =ref 0;;
let tam_str = String.length str -1;;
let aux_char = 'A';;
let b_aux1 = ref false;;
exception Out_of_loop;;

try
  while !i <= tam_str do
    let c_r = str.[!i] in
    if c_r = aux_char then(
      b_aux1 := true;
      i := !i +1;
    )
    else(
      b_aux1 := false;
      raise Out_of_loop
    )
  done;
with Out_of_loop ->();
if !b_aux1 then
  print_endline "1"
else
  print_endline "0";
;;

I expected the program to write the string "1" but it is returning "unit". But I don't understand why ... Can someone explain why?

Upvotes: 0

Views: 46

Answers (1)

Guillaume Melquiond
Guillaume Melquiond

Reputation: 1263

Be careful of the precedence of the various constructs. You have written

try ...
with Out_of_loop ->
  begin
    ();
    if !b_aux1 then ...
  end

while I suppose you wanted to write

begin
  try ...
  with Out_of_loop -> ()
end;
if !b_aux1 then ...

Upvotes: 2

Related Questions