ocaml - 在 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
#
这个问题在这里已经有了答案。还有另一个与此类似的问题,我在提出问题之前已经解决了这个问题,但是我不清楚(可能是因为我是一个完整的新手。其他新手可能会面临类似的困惑。)如何从接受的答案中解决问题。
解决方案
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,反之亦然。这是一个功能,而不是一个错误。
推荐阅读
- openshift - openshift:允许服务帐户创建项目
- pandas - pylint, pandas : 与 True 的比较应该只是 'expr' 或 'expr is True' (singleton-comparison)
- c# - 需要从整个 SQL Server 数据库中过滤掉一个人
- c# - 自定义控件中的数据模板
- jenkins - Grep Jenkins 输出和电子邮件用户
- java - 父数组中的Java子引用类型
- c# - SqlTransaction 未提交 - C#
- ajax - scalajs getCause on Ajax.post onFailure
- c# - C# MVC App 双重登录
- asp.net - 找不到类型或命名空间名称“Func<,>”(您是否缺少 using 指令或程序集引用?