Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a formatted string in OCaml?

Tags:

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?

like image 393
Jackson Tale Avatar asked Jun 15 '13 10:06

Jackson Tale


2 Answers

You can use Printf.sprintf:

# Printf.sprintf "Hello %s %d\n" "world" 123;;
- : string = "Hello world 123\n"
like image 56
zch Avatar answered Nov 10 '22 21:11

zch


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

like image 7
Jeffrey Scofield Avatar answered Nov 10 '22 21:11

Jeffrey Scofield