user2821649
user2821649

Reputation: 57

OCaml: reference cells, Some, None

I am reading the book by Jason, and face the following code.

let x = ref None;;
let one_shot y =
    match !x with
        None ->
            x := Some y;
            y
      | Some z -> z;;

I do not understand the meaning of Some and None here.

Upvotes: 0

Views: 3711

Answers (3)

james woodyatt
james woodyatt

Reputation: 2196

Those are constructors for the built-in option type, defined as follows:

type 'a option = None | Some of 'a

It's a generally useful sum type for representing an optional value, used as such in the example shown in your question.

Worth noting here, it's a built-in type (rather than provided in the Pervasives module) because it's used for inference of the types of functions with optional arguments.

For example, consider the following:

let f ?x () =
  match x with
  | Some x -> x
  | None -> 0

This function has the following type:

val f: ?x:int -> unit -> int

Upvotes: 1

mrd abd
mrd abd

Reputation: 858

None is something like is not set or null. if a value matches None, this value is not set.

Some is something like is set with something or not null. if a value matches Some z, this value has a value z.

here, the function one_shot looks !x (the variable in address x). if its None then sets with y and returns y and if is Some z then returns z

Upvotes: 2

gasche
gasche

Reputation: 31459

They are constructors of a built-in OCaml datatype, that you could have defined yourself as such:

type 'a option =
  | None
  | Some of 'a

This means that None if of type 'a option for any 'a, and, for example, Some 3 is an int option.

Upvotes: 1

Related Questions