Option type

From Infogalactic: the planetary knowledge core
Jump to: navigation, search

Lua error in package.lua at line 80: module 'strict' not found.

<templatestyles src="Module:Hatnote/styles.css"></templatestyles>

In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions which may or may not return a meaningful value when they are applied. It consists of either an empty constructor (called None or Nothing), or a constructor encapsulating the original data type A (written Just A or Some A). Outside of functional programming, these are known as nullable types.

  • In the Haskell language, the option type (called Maybe) is defined as data Maybe a = Nothing | Just a.
  • In the Idris language, the option type is also defined as data Maybe a = Nothing | Just a.
  • In the Agda language, the option type is called Maybe with variants nothing and just a.
  • In the Coq language, the option type is defined as Inductive option (A:Type) : Type := | Some : A -> option A | None : option A..
  • In the OCaml language, the option type is defined as type 'a option = None | Some of 'a.
  • In the Scala language, the option type is defined as parameterized abstract class '.. Option[A] = if (x == null) None else Some(x)...
  • In the Standard ML language, the option type is defined as datatype 'a option = NONE | SOME of 'a.
  • In the Rust language, it is defined as enum Option<T> { None, Some(T) }.
  • In the Swift language, it is defined as enum Optional<T> { case None, Some(T) } but is generally written as T? and is initialized with either a value or nil.
  • In the Julia language, the option type is called Nullable{T}.
  • In the Java language since version 8, the option type is defined as parameterized final class Optional<T>.
  • In the C++ language proposed extensions, the option type is defined as the template class template<class T> class optional.
  • In the Kotlin language, it is defined as T?. [1]

In type theory, it may be written as: A^{?} = A + 1.

In languages that have tagged unions, as in most functional programming languages, option types can be expressed as the tagged union of a unit type plus the encapsulated type.

In the Curry-Howard correspondence, option types are related to the annihilation law for ∨: x∨1=1.

An option type can also be seen as a collection containing either a single element or zero elements.

The option monad

The option type is a monad under the following functions:

\text{return}\colon A \to A^{?} = a \mapsto \text{Just} \, a
\text{bind}\colon A^{?} \to (A \to B^{?}) \to B^{?} = a \mapsto f \mapsto \begin{cases} \text{Nothing} & \text{if} \ a = \text{Nothing}\\ f \, a' & \text{if} \ a = \text{Just} \, a' \end{cases}

We may also describe the option monad in terms of functions return, fmap and join, where the latter two are given by:

\text{fmap} \colon (A \to B) \to A^{?} \to B^{?} = f \mapsto a \mapsto \begin{cases} \text{Nothing} & \text{if} \ a = \text{Nothing}\\ \text{Just} \, f \, a' & \text{if} \ a = \text{Just} \, a' \end{cases}
\text{join} \colon {A^{?}}^{?} \to A^{?} = a \mapsto \begin{cases} \text{Nothing} & \text{if} \ a = \text{Nothing}\\ \text{Nothing} & \text{if} \ a = \text{Just} \, \text{Nothing}\\ \text{Just} \, a' & \text{if} \ a = \text{Just} \, \text{Just} \, a' \end{cases}

The option monad is an additive monad: it has Nothing as a zero constructor and the following function as a monadic sum:

\text{mplus} \colon A^{?} \to A^{?} \to A^{?} = a_1 \mapsto a_2 \mapsto \begin{cases} \text{Nothing} & \text{if} \ a_1 = \text{Nothing} \and a_2 = \text{Nothing}\\ \text{Just} \, a'_2 & \text{if} \ a_1 = \text{Nothing} \and a_2 = \text{Just} \, a'_2 \\ \text{Just} \, a'_1 & \text{if} \ a_1 = \text{Just} \, a'_1 \end{cases}

In fact, the resulting structure is an idempotent monoid.

Examples

Ada

Ada does not implement option-types directly, but rather employs an abstract method of parameterization known as discriminated records; for an optional type a Boolean is used, the following example is combined with generic packages to create an option type for any constrained, non-limited type:

Generic
  -- Any non-limited, constrained type.
  Type Element is private;
Package Optional_Pkg is
  -- The following record has no fields when Has_Element is False;
  -- however, when it is True, the Data field exists.
  Type Optional( Has_Element : Boolean ) is record;
    case Has_Element is
      when False => Null;
      when True  => Data : Element;
    end case;
  end record;
End Optional_Pkg;


Scala

Scala implements Option as a parameterized type, so a variable can be an Option, accessed as follows:[2]

// Defining variables that are Options of type Int
val res1: Option[Int] = Some(42)
val res2: Option[Int] = None

// sample 1 :  This function uses pattern matching to deconstruct Options
def compute(opt: Option[Int]) = opt match {
  case None => "No value"
  case Some(x) => "The value is: " + x
}

// sample 2 :  This function uses monad method
def compute(opt: Option[Int]) = opt.fold("No Value")(v => "The value is:" + v )

println(compute(res1))  // The value is: 42
println(compute(res2))  // No value

There are two main ways to use an Option value. The first one, not the best, is the pattern matching as in the first example. The second one, the best practice, is the monad method as in the second example. In this way, the program is safe as it cannot generate any exception or error (e.g. by trying to obtain the value of an Option variable that is equal to None). Therefore, it essentially works as a type-safe alternative to the null value.

F#

(* This function uses pattern matching to deconstruct Options *)
let compute = function
  | None   -> "No value"
  | Some x -> sprintf "The value is: %d" x

printfn "%s" (compute <| Some 42)(* The value is: 42 *)
printfn "%s" (compute None)      (* No value         *)

Haskell

-- This function uses pattern matching to deconstruct Maybes
compute :: Maybe Int -> String
compute Nothing  = "No value"
compute (Just x) = "The value is: " ++ show x

main :: IO ()
main = do
    print $ compute (Just 42) -- The value is: 42
    print $ compute Nothing -- No value

Swift

func compute(x: Int?) -> String {
  // This function uses optional binding to deconstruct optionals
  if let y = x {
    return "The value is: \(y)"
  } else {
    return "No value"
  }
}

print(compute(42)) // The value is: 42
print(compute(nil)) // No value
func compute(x: Int?) -> String {
  // This function explicitly unwraps an optional after comparing to nil
  return nil == x ? "No value" : "The value is: \(x!)"
}

print(compute(42)) // The value is: 42
print(compute(nil)) // No value
func compute(x: Int?) -> String {
  // This function uses pattern matching to deconstruct optionals
  switch x {
  case .None: 
    return "No value"
  case .Some(let y): 
    return "The value is: \(y)"
  }
}

print(compute(42)) // The value is: 42
print(compute(nil)) // No value

Rust

Rust allows using either pattern matching or optional binding to deconstruct the Option type:

fn main() {
    // This function uses pattern matching to deconstruct optionals
    fn compute(x: Option<i32>) -> String {
        match x {
            Some(a) => format!("The value is: {}", a),
            None    => format!("No value")
        }
    }

    println!("{}", compute(Some(42))); // The value is: 42
    println!("{}", compute(None)); // No value
}
fn main() {
    // This function uses optional binding to deconstruct optionals
    fn compute(x: Option<i32>) -> String {
        if let Some(a) = x {
            format!("The value is: {}", a)
        } else {
            format!("No value")
        }
    }

    println!("{}", compute(Some(42))); // The value is: 42
    println!("{}", compute(None)); // No value
}

Julia

Julia requires explicit deconstruction to access a nullable value:

function compute(x::Nullable{Int})
    if !isnull(x)
        println("The value is: $(get(x))")
    else
        println("No value")
    end
end
julia> compute(Nullable(42))
The value is: 42
j←←←←←←←ulia> compute(Nullable{Int}())
No value

See also

References

  1. Lua error in package.lua at line 80: module 'strict' not found.
  2. Lua error in package.lua at line 80: module 'strict' not found.