如何在 Ocaml 的 float 类型中表示空值

发布于 2024-10-17 11:49:00 字数 213 浏览 4 评论 0原文

我知道这可能看起来非常基本,但基本上,我想说在模式匹配中

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我很坚强 2024-10-24 11:49:00

你不能。这是一个设计选择。许多语言允许任何值为空。这种方法的问题在于,当程序员不期望时,值会为空,或者代码必须检查每个输入值是否为空。

OCaml 采用的方法是,如果一个值可能为 null,则必须将其显式标记为 null。这是通过选项类型完成的:

match value with
  | None -> failwith "Empty"
  | Some value -> (* do something *)

但是,如果将其直接替换到程序中,则将无法编译,因为 OCaml 会发现该“值”实际上不能为空。无论创建什么,都需要更新以指示它何时返回“空”值(无):

let safe_divide numerator denominator =
  if denominator <> 0. then
    Some (numerator /. denominator)
  else
    None (* division by zero *)

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:

match value with
  | None -> failwith "Empty"
  | Some value -> (* do something *)

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):

let safe_divide numerator denominator =
  if denominator <> 0. then
    Some (numerator /. denominator)
  else
    None (* division by zero *)
故事灯 2024-10-24 11:49:00

正如delnan所说,OCaml中没有null。如果适合您的问题,您可以做的是在模式匹配中使用选项,如下所示:

let your_function x = 
   match x with
    | None -> failwith "Empty"
    | Some f -> #do something

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:

let your_function x = 
   match x with
    | None -> failwith "Empty"
    | Some f -> #do something
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文