Function that calls a function with the terminal temporarily set to raw mode
The sad fact is that your code should be even uglier. If f() throws an exception, you won't restore the resources correctly.

Idiomatic OCaml recommends that a recurring pattern can be described with a function. So you would define a function that takes:


a resource ('a)
a function to execute with the resource ('a -&gt; 'b)
and a function to free the resource ('a -&gt; unit)


The signature becomes:

val bracket : 'a -&gt; ('a -&gt; 'b) -&gt; ('a -&gt; unit) -&gt; 'b


The bracket function would do the ugly let res = f() thing, but also wrap it with a try-catch.

UPDATE: The next version of OCaml (v4.08.0) looks like it will have a finally-type function added to the standard library: https://github.com/ocaml/ocaml/pull/1855