简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM