nyluje
nyluje

Reputation: 3773

This expression has type unit but an expression was expected of type string

I am new to Ocaml,

I am trying to figure out how to "cast" a "unit" type constant to "string" type.

I've seen there was string_of_intfunction to do so with integer type but cannot find the equivalent for "unit" type. Maybe there is something to do with the Printf, I did so with boolean using Printf.printf "%B" (x); but I haven't figure out what would be the one to use in "unit" type case.

Here is my code example:

Function defined:

let displayList l = List.iter(fun x -> print_string(string_of_int x^";")) l;;

Using the function above:

  1. The following expression works: let _ = displayList [5;5;6;5;5;6;3] in (); and displays "5;5;6;5;5;6;3;".
  2. The following expression does not work: let _ = print_string ("[" ^ displayList [5;5;6;5;5;6;3] ^ "]") in ();. It throws error message "This expression has type unit but an expression was expected of type string".

Upvotes: 0

Views: 926

Answers (1)

sonologico
sonologico

Reputation: 764

You are mixing up the printed and the returned values.

displayList doesn't return a string. It prints a string and then returns an unit. The string concatenation operator (^) expects two strings, but, as mentioned, the return type of displayList is unit.

Making a string out of unit wouldn't do what it seems you are expecting. displayList would still print 5;5;6;5;5;6;3; and your expression would return a string like "[()]".

If you intended to print [5;5;6;5;5;6;3;], a solution (using what you already have) could be

let displayList l =
  print_char '[';
  List.iter(fun x -> print_string(string_of_int x^";")) l;
  print_char ']'
;;

Upvotes: 1

Related Questions