2017-10-25 10:35 GMT+02:00 Richard W.M. Jones <rich@annexia.org>:
On Tue, Oct 24, 2017 at 09:00:05PM +0200, Petter A. Urkedal wrote:
> On 24 October 2017 at 15:30, Richard W.M. Jones <rich@annexia.org> wrote:
> > Since I first used OCaml I have wished for a simple (and type safe)
> > return statement.
>
> It's possible to wrap a bit type (and exception) safety about
> exceptions used for return:
>
>   val with_return : (('a -> 'b) -> 'a) -> 'a
>
>   let with_return (type b) f =
>     let exception Return of b in
>     try f (fun y -> raise (Return y)) with Return y -> y
>
> E.g.
>
>   with_return (fun return -> List.iter (function 0 -> () | i -> return
> i) [0; 0; 24; 0]; -1);;

Thanks, that's interesting.

        --

As mine was a bit of a "Hit and run" comment, let me expand on
why a return statement is useful for the kind of dull code that
I write.

I often have to write functions of the form:

  let f () =
    if some_problem then (
      printf "sorry, can't do that\n";
      (* return *)
    )
    else if some_other_problem then (
      printf "sorry, can't do that either\n";
      (* return *)
    )
    else (
      match something with
      | None ->
         (* return *)
      | Some v ->
         (* finally we get to do some work! *)
         ...
    )


Hi Richard,

isn't that a context where error monads do a pretty decent job?

check_some_problem () >>= fun () ->
check_some_other_problem () >>= fun () ->
expect_something () >>= fun something ->
finally_do something

Cheers,
  Philippe.