Ocaml option , Some

hey, can someone help me analyze the following function?
fun → if r="-a" then Some (Rat(1,3)) else if r="_b" then Some (Rat(1,6)) else Some (Rat(0,1));;
I am only interested in Some (Rat(n,n1)) part. what Some will do in this case?
and
type value = Rat of rat | Fun of var * state * expr and state = var → value option ;;
i am wondering about value option part.

A value of type 'a option denotes a value of type 'a that can be present or not: Some x represents the case where the value is present and None the absence of such a value. Note that you can format your code with ```ocaml ```. For instance:

fun r ->
  if r="-a" then Some (Rat(1,3))
  else if r="_b" then Some (Rat(1,6))
  else Some (Rat(0,1))
1 Like

OCaml has variant data types that are used to represent variants of the same entity, e.g.,

type figure = Circle | Rect

Each variant may have its own varinat-specific values, e.g.,

type figure = Circle of int | Rect of int * int

The capitalized part is called constructor and can be used to construct values, so Circle 5 is a figure that is a circle with the specified radius. Another example, Rect (3,4) creates a figure that represents a rectangle. Constructors are also used to pattern match on variants of the type. You may think of this as a downcasting, e.g.,

let area : figure -> int = function
  | Circle r -> 3 * r * r 
  | Rectangle (x,y) -> x * y

So, instead of using class hierarchies and visitors, we use a simple and efficient representation that relies on variants and records, together known as algebraic data types.

Now back to option. This is a type from the OCaml standard library that has the following definition,

type 'a option = Some of 'a | None

So it that int option denotes a type of values that have two variants Some x where x has type int and None that doesn’t have any payload. This 'a denotes a parameterized type. So that 'a option is in fact a family of types. But this is another lesson. Please, consider reading the OCaml tutorial, it is short and easy. There are also a lot of books about OCaml.

3 Likes