Generic
-- Any constrained & non-limited type.
Type Element_Type is private;
Package Optional_Type is
-- When the discriminant, Has_Element, is true there is an element field,
-- when it is false, there are no fields (hence the null keyword).
Type Optional( Has_Element : Boolean ) is record
case Has_Element is
when False => Null;
when True => Element : Element_Type;
end case;
end record;
end Optional_Type;
Scala
Scala implements Option as a parameterized type, so a variable can be an Option, accessed as follows:[6]
object Main {
// This function uses pattern matching to deconstruct `Option`s
def computeV1(opt: Option[Int]): String =
opt match {
case Some(x) => s"The value is: $x"
case None => "No value"
}
// This function uses the built-in `fold` method
def computeV2(opt: Option[Int]): String =
opt.fold("No value")(x => s"The value is: $x")
def main(args: Array[String]): Unit = {
// Define variables that are `Option`s of type `Int`
val full = Some(42)
val empty: Option[Int] = None
// computeV1(full) -> The value is: 42
println(s"computeV1(full) -> ${computeV1(full)}")
// computeV1(empty) -> No value
println(s"computeV1(empty) -> ${computeV1(empty)}")
// computeV2(full) -> The value is: 42
println(s"computeV2(full) -> ${computeV2(full)}")
// computeV2(empty) -> No value
println(s"computeV2(empty) -> ${computeV2(empty)}")
}
}
Two main ways to use an Option value exist. The first, not the best, is the pattern matching, as in the first example. The second, the best practice is a monadic approach, as in the second example. In this way, a program is safe, as it can generate no exception or error (e.g., by trying to obtain the value of an Option variable that is equal to None). Thus, it essentially works as a type-safe alternative to the null value.
OCaml
OCaml implements Option as a parameterized variant type. Options are constructed and deconstructed as follows:
(* This function uses pattern matching to deconstruct `option`s *)
Do'stlaringiz bilan baham: |