Mr. Nobody
Mr. Nobody

Reputation: 195

Printing user defined types in Ocaml

I am defining a new type which is basically a string. How to print the value ?

# type mytp = Mytp of string;;
type mytp = Mytp of string
# let x = Mytp "Hello Ocaml";;
val x : mytp = Mytp "Hello Ocaml"
# print_endline x;;
Error: This expression has type mytp but an expression was expected of type
         string
# 

This question already has answer here. There is another question similar to this, which I had went through before asking the question, however I was not clear (maybe because I am a complete newbie. Other newbies might face similar confusion.) how to solve the problem from the accepted answer.

Upvotes: 0

Views: 797

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

The type of print_endline is string -> unit. So you can't pass a value of type mytp.

You can write a function to print a value of type mytp:

let print_mytp (Mytp s) = print_endline s

You can write a function to convert mytp to string:

let string_of_mytp (Mytp s) = s

Then you can print like so:

print_endline (string_of_mytp x)

OCaml will not allow you to use mytp where string is expected, or vice versa. This is a feature, not a bug.

Upvotes: 2

Related Questions