Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 867
Jacob Avatar asked Feb 16 '11 18:02

Jacob


1 Answers

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 *)
like image 99
jynxzero Avatar answered Sep 28 '22 07:09

jynxzero