Mr Smith
Mr Smith

Reputation: 113

is it possible to reproduce python's string interpolation in 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?

Upvotes: 11

Views: 2105

Answers (3)

camlspotter
camlspotter

Reputation: 9030

You can do it by a prefix op, instead of infix:

let (!%) = Printf.sprintf

If you want just a concise way of writing sprintf, it is enough.

As Tobu mentioned you require P4 if you want Python like special syntax. I believe it must be too complicated.

Upvotes: 0

Norman Ramsey
Norman Ramsey

Reputation: 202505

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.

Upvotes: 8

user219911
user219911

Reputation: 36

In theory, it does not seem any more difficult to use a format to produce the type (typ1 * typ2 * ... * typn) -> string than typ1 -> typ2 -> ... -> typn -> string. That is, perhaps, with the exception of recursive formats %( fmt %). Does anyone actually use those?

In practice, though, the OCaml implementors chose the latter form, and implemented typesystem hacks for that form, not for the former one. So I am afraid the answer is that short of patching the compiler, you're stuck with the curried form of format string substitution.

Upvotes: 1

Related Questions