Help getting this code to compile

Code snippet (ml file):


module H = Tyxml.Html 


let render param =
  H.html (H.head (H.title (H.txt "title")) [])
  (H.body [ ]);;


let html_to_string html =
  Format.asprintf "%a" H.pp() html;;

Error:

Error:

File "server/a_07_template.ml", line 10, characters 18-22:
10 |   Format.asprintf "%a" H.pp() html;;
                       ^^^^
Error: This expression has type
         ('a -> 'b, Format.formatter, unit, unit, unit, 'a -> 'b)
         CamlinternalFormatBasics.fmt
       but an expression was expected of type
         ('a -> 'b, Format.formatter, unit, unit, unit, string)
         CamlinternalFormatBasics.fmt
       Type 'a -> 'b is not compatible with type string 
File "server/a_07_template.ml", line 10, characters 18-22:
10 |   Format.asprintf "%a" H.pp() html;;
                       ^^^^
Error: This expression has type
         ('a -> 'b, Format.formatter, unit, unit, unit, 'a -> 'b)
         CamlinternalFormatBasics.fmt
       but an expression was expected of type
         ('a -> 'b, Format.formatter, unit, unit, unit, string)
         CamlinternalFormatBasics.fmt
       Type 'a -> 'b is not compatible with type string 

Code I was reading at at the time: dream/tyxml.re at master · aantron/dream · GitHub

From what I know from “%a”, my first attempt would be to change H.pp() to H.pp

let html_to_string html =
  Format.asprintf "%a" (H.pp ()) html;;
3 Likes

let f () : blah = ...

I understand the difference between f (has type () -> blah) and f () has type blah.

What is the difference between f() and f () (note the space between the f and the ()). I don’t understand this.

There is no difference — OCaml is whitespace insensiive.

The fact that there is no space between and the parenthesis f() imparts no additional meaning to the program.

The problem with your original code:

Format.asprintf "%a" H.pp() html;;

was that it was effectively:

  Format.asprintf "%a" H.pp () html

so Format.asprintf was receiving 4 arguments: "%a", H.pp, () and html.

The error is fixed by adding parentheses to explicitly group H.pp () into a single expression.

3 Likes