Option Type
The option type is often present in most functional programming languages, even though it may have different names, it represents the same concept.
It’s either data is present, or there’s nothing at all
type option('a) = None | Some('a)
This is the option type. Its got a type argument and it either returns a None or Some('a).
In haskell its called a Maybe
data Maybe =
| Nothing
| Just
So its either a just of the value or nothing.
As always we can pattern match on the option type
let age = Some(23)
switch (age) {
| None => print_endline("Passed on")
| Some(ageinyrs) => print_endline("You are " ++ str_of_int(ageinyrs) ++ " yrs old.")
}
Since option accepts a type Argument it can carry a Some of any data type.(ints, lists, strings)
let students = None;
switch (students) {
| None => print_endline("This class hasn't admitted anyone")
| Some([]) => print_endline("The class is empty , the students may have gone for lunch")
| Some(fullClass) => print_endline("Everyone is present")
}
The option type also forces you to type check for every scenario.
Try deleting one branch in the code above. (The last branch to be precise)
let students = None;
switch (students) {
| None => print_endline("This class hasn't admitted anyone")
| Some([]) => print_endline("The class is empty , the students may have gone for lunch")
}
You’ll instantly get a warning that this pattern-matching is not exhaustive.
Add it back up and lets continue.
Some(Js Interop)
Lets assume we have a js function in a file that returns true if age is provided but false if age is absent (null or undefined)
A few functions that you are to keep in mind for this small demo
- string_of_bool => Converts a bool to a string
- Js.Nullable.t('a) => Used when value coming from Js can be undefined or null.
- Js.Nullable.fromOption => Converts an option to a Js.Nullable
Lets begin
// bool.js
export default num => {
if (num) return true;
else return false;
};
[@bs.module] external isAgePresent : (Js.Nullable.t(int)) => bool = "./bool";
let age = None;
isAgePresent(Js.Nullable.fromOption(age))
[@bs.module] external isAgePresent : (Js.Nullable.t(int)) => bool = "./bool";
Imports the js function
let age = None;
isAgePresent(Js.Nullable.fromOption(age))
Js.Nullable.fromOption converts an option to either a null or the unwrapped value if present.
None gets converted to undefined Some(12) gets converted to 12.
Js.Nullable.toOption converts a Js.Nullable.tto an option. Either
None when undefined or
Some(x) when the value is defined.