Jackson Tale
Jackson Tale

Reputation: 25812

How to get a formatted string in OCaml?

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?

Upvotes: 15

Views: 29734

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66793

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.)

Upvotes: 9

zch
zch

Reputation: 15278

You can use Printf.sprintf:

# Printf.sprintf "Hello %s %d\n" "world" 123;;
- : string = "Hello world 123\n"

Upvotes: 24

Related Questions