15

In OCaml, I can use Printf.printf to output formatted string, like

Printf.printf "Hello %s %d\n" world 123

However, printf is a kind of output.


What I wish for is not for output, but for a string. For example, I want

let s = something "Hello %s %d\n" "world" 123

then I can get s = "Hello World 123"


How can I do that?

Wilfred Hughes
  • 29,846
  • 15
  • 139
  • 192
Jackson Tale
  • 25,428
  • 34
  • 149
  • 271

2 Answers2

22

You can use Printf.sprintf:

# Printf.sprintf "Hello %s %d\n" "world" 123;;
- : string = "Hello world 123\n"
zch
  • 14,931
  • 2
  • 41
  • 49
  • can I define like this: `let fmt = "Hello %s %d\n";; Printf.sprintf fmt "world" 123`? – Jackson Tale Jun 15 '13 at 11:54
  • 3
    @JacksonTale, I'm not really sure. It seems you can do `let fmt = Printf.sprintf "Hello %s %d\n";; fmt "world" 123;;` however. – zch Jun 15 '13 at 12:05
  • @JacksonTale: if you do it that way, it will infer the wrong type (string instead of format thingy). In OCaml there is an "overload" for string literals between strings and format thingies. To make it infer the right thing, you must use `format_of_string` (which is an identify function, but helps the type system): `let fmt = format_of_string "Hello %s %d\n";; Printf.sprintf fmt "world" 123`. Or maybe you can just do `(fun fmt -> Printf.sprintf fmt "world" 123) "Hello %s %d\n"` if that is sufficient. – newacct Jun 16 '13 at 06:17
8

You can do this:

$ ocaml
        OCaml version 4.00.1

# let fmt = format_of_string "Hello %s %d";;
val fmt : (string -> int -> '_a, '_b, '_c, '_d, '_d, '_a) format6 = <abstr>
# Printf.sprintf fmt "world" 123;;
- : string = "Hello world 123"

The format_of_string function (as the name implies) transforms a string literal into a format. Note that formats must ultimately be built from string literals, because there is compiler magic involved. You can't read in a string and use it as a format, for example. (It wouldn't be typesafe.)

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108