在 Ocaml 中打印用户定义的类型

Printing user defined types in Ocaml

我正在定义一个基本上是字符串的新类型。如何打印值?

# 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
# 

此问题已有答案here。 还有一个类似的question,我在问这个问题之前经历过,但是我不清楚(可能因为我是一个完整的新手。其他新手可能面临类似的困惑。)如何解决问题从接受的答案。

print_endline的类型是string -> unit。所以你不能传递类型为 mytp 的值。

您可以编写一个函数来打印 mytp 类型的值:

let print_mytp (Mytp s) = print_endline s

您可以编写一个函数将 mytp 转换为字符串:

let string_of_mytp (Mytp s) = s

然后你可以这样打印:

print_endline (string_of_mytp x)

OCaml 不允许您在需要字符串的地方使用 mytp,反之亦然。这是一个功能,不是错误。