In python, one can use printf like formatting with the "%" operator:
"i am %d years old" % 99
or
"%s is %d years old" % ("bob", 101)
Is there a way to get the same concise syntax in Ocaml, for arbitrary numbers of arguments?
For a single argument, the following works:
let (%) = Printf.sprintf in ... "i am %d years old" % 99
Is there a way that works for arbitrary numbers of arguments?
Python 3.6 added new string interpolation method called literal string interpolation and introduced a new literal prefix f . This new way of formatting strings is powerful and easy to use. It provides access to embedded Python expressions inside string constants.
String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.
It depends what you mean by arbitrary numbers of arguments:
I don't believe there is a way to write a function in OCaml that can accept and unpack a tuple of arbitrary arity (e.g., both (1, "bob")
and ("joe", "bob", "briggs")
).
The Caml Way of handling multiple arguments is not through tuples but by currying. If you're willing to do that, then you can just use Printf.sprintf
.
If you really want an infix operator, e.g., something like
"%s-%s %s is the best movie reviewer" % "joe" "bob" "briggs"
then you're out of luck, because function application binds tighter than any infix operator. You could write
("%s-%s %s is the best movie reviewer" % "joe") "bob" "briggs"
but to me that seems kind of beside the point—not the droids you're looking for.
So if your question is:
Can I define, in Objective Caml, an infix version of
sprintf
that accepts an arbitrary number of arguments?
The answer is no.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With