Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to reproduce python's string interpolation in ocaml?

Tags:

printf

ocaml

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?

like image 457
Mr Smith Avatar asked Feb 06 '10 15:02

Mr Smith


People also ask

Does Python support string interpolation?

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.

How is string interpolation performed in Python?

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.


1 Answers

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.

like image 52
Norman Ramsey Avatar answered Sep 18 '22 20:09

Norman Ramsey