Search code examples
while-looptry-catchocamlimperative-programming

return type after while in a try


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 ?


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