Why does failwithf expect an unit at the end?

53 views
Skip to first unread message

Maverick Woo

unread,
Jun 29, 2015, 2:30:21 PM6/29/15
to ocaml...@googlegroups.com
Hi,

Out of curiosity, may I know the reason why failwithf (and invalid_argf) wants an unit at the end of an invocation? What advantage does this bring over a version that does not need an ending unit?

Thank you!

Maverick

Ben Millwood

unread,
Jun 30, 2015, 6:46:46 AM6/30/15
to ocaml...@googlegroups.com
It enables better format string checking. The problem is that failwith-like functions have fully polymorphic return types (they don't return, so they can claim to return whatever type they like), and in particular [failwith "oh no"] can act as a function and take further parameters.

Thus, if you have a failwith-like function that takes a variable number of parameters, you can easily lose the static checking that you aren't giving too many. For example, you can define a unitless failwithf:

utop # let f fmt = ksprintf (fun s -> failwith s) fmt;;
val f : ('a, unit, string, 'b) format4 -> 'a = <fun>

Now [f "%d" 4] has type ['a]. Unfortunately, this type can be unified with, say, [int -> 'b], so [f "%d" 4 5] is no longer a type error, it just raises [Failure "4"].

If, on the other hand, you define failwithf:

utop # let f fmt = ksprintf (fun s -> fun () -> failwith s) fmt;;
val f : ('a, unit, string, unit -> 'b) format4 -> 'a = <fun>

Now [f "%d" 4 5] complains that 5 doesn't match type unit. The () parameter is serving as a signpost for "end of format arguments".

--
You received this message because you are subscribed to the Google Groups "ocaml-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ocaml-core+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages