Question

Almost for the first time I'm trying to write imperative code in ocaml to try to answer a question on this website, but I'm facing a little problem.

let f() =
try
  while true do
    ()
  done
with
    _ -> 2

He doesn't like this, because he thinks that this function returns unit, as it is in the try block, but the try block returns an int. So it works if I add 3 after "done", but it's really ugly since the 3 is really never returned.

How do you do this ?

Was it helpful?

Solution

Use assert false, which always raises an exception and therefore can be used where any type is expected:

let f() =
  try
    while true do
      ()
    done;
    assert false
  with
      _ -> 2

OTHER TIPS

  • while (and for) loops in OCaml are expressions that return a result of type unit.

  • In addition, when you write (try expr1 with _ -> expr2), this is an OCaml expression of type t, if expr1 and expr2 are well typed of type t (more complicated with polymorphism)

  • But, in your example, try branch has type unit whereas with branch has type int. The OCaml compiler is not happy with that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top