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

时间:2019-02-08 01:30:33

标签: ocaml user-defined-types

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

# 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,我在问这个问题之前就经历过,但是我不清楚(也许因为我是一个完整的新手。其他新手可能会遇到类似的困惑。)接受的答案。

1 个答案:

答案 0 :(得分:2)

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,反之亦然。这是一个功能,而不是错误。

相关问题