打印用户OCaml中定义的类型

问题描述 投票:0回答:1

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

# 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,但是我并不清楚(也许是因为我是一个完整的新手。其他新手可能会面临类似的困惑。)如何从接受的答案解决问题。

ocaml user-defined-types
1个回答
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其中字符串是预期,反之亦然。这是一个功能,而不是一个错误。

© www.soinside.com 2019 - 2024. All rights reserved.