首页 > 解决方案 > 在 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
# 

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

标签: ocamluser-defined-types

解决方案


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


推荐阅读