如何在 Ocaml 的 float 类型中表示空值
我知道这可能看起来非常基本,但基本上,我想说在模式匹配中
match value with
Null-> failwith "Empty"
|value-> #do something
我已经尝试过 null 或 none 的任何变体,并且还尝试了无法使用的单位,因为值是浮点数。
我很困惑,任何帮助将不胜感激
I know this may seem very basic but basically, I want to say in pattern matching
match value with
Null-> failwith "Empty"
|value-> #do something
I've tried any variation of null or none, and have also tried unit which cannot be used because value is a float.
I am stumped and any help would be appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能。这是一个设计选择。许多语言允许任何值为空。这种方法的问题在于,当程序员不期望时,值会为空,或者代码必须检查每个输入值是否为空。
OCaml 采用的方法是,如果一个值可能为 null,则必须将其显式标记为 null。这是通过选项类型完成的:
但是,如果将其直接替换到程序中,则将无法编译,因为 OCaml 会发现该“值”实际上不能为空。无论创建什么,都需要更新以指示它何时返回“空”值(无):
You can't. This is a design choice. Many languages allow any value to be null. The problem with this approach is that, values are null when the programmer doesn't expect it, or the code has to be littered with checks of every input value for nulls.
OCaml takes the approach that, if a value could be null, then it must be explicitly marked as such. This is done with the option type:
However, if you substitute that directly into your program, if will fail to compile, because OCaml will spot that "value" can't actually be null. Whatever is creating will need to be updated to indicate when it is returning a "null" value (None):
正如delnan所说,OCaml中没有
null
。如果适合您的问题,您可以做的是在模式匹配中使用选项,如下所示:As delnan said, there is no
null
in OCaml. What you can do, if it is appropriate for your problem, is to use options in pattern matching like this: