Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting OCaml strings to format6

Tags:

ocaml

The following code does not compile:

let x = "hello" in
Printf.printf x

The error is:

Error: This expression has type string but an expression was expected of type
     ('a, out_channel, unit) format =
       ('a, out_channel, unit, unit, unit, unit) format6

1) Can someone give an explanation of the error message?

2) And why would a string cannot be passed to printf ?

like image 850
Nicolas Viennot Avatar asked May 05 '12 03:05

Nicolas Viennot


People also ask

How do I turn an object into a string in OCaml?

In Java you might use the overloaded + operator to turn all objects into strings: But OCaml values are not objects, and they do not have a toString () method they inherit from some root Object class. Nor does OCaml permit overloading of operators.

Does OCaml permit overloading of operators?

Nor does OCaml permit overloading of operators. Long ago though, FORTRAN invented a different solution that other languages like C and Java and even Python support. The idea is to use a format specifier to —as the name suggest— specify how to format output.

Does OCaml support ToString() method?

But OCaml values are not objects, and they do not have a toString () method they inherit from some root Object class. Nor does OCaml permit overloading of operators. Long ago though, FORTRAN invented a different solution that other languages like C and Java and even Python support.

What are the printing functions in OCaml 2?

2.6. Printing OCaml has built-in printing functions for a few of the built-in primitive types: print_char, print_string, print_int, and print_float. There’s also a print_endline function, which is like print_string, but also outputs a newline.


1 Answers

The first argument to printf must be of type ('a, out_channel, unit) format not string. String literals can be automatically converted to an appropriate format type, but strings in general can't.

The reason for that is that the exact type of a format string depends on the contents of the string. For example the type of the expression printf "%d-%d" should be int -> int -> () while the type of printf "%s" should be string -> (). Clearly such type checking is impossible when the format string is not known at compile time.

In your case you can just do printf "%s" x.

like image 157
sepp2k Avatar answered Oct 11 '22 14:10

sepp2k