开发者

How do I represent an null value in type float for Ocaml

开发者 https://www.devze.com 2023-02-10 17:44 出处:网络
I know this may seem very basic but basically, I want to say in pattern matching match value with Null-> failwi开发者_开发问答th \"Empty\"

I know this may seem very basic but basically, I want to say in pattern matching

match value with
  Null-> failwi开发者_开发问答th "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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号