The Option
structure
The Option structure defines the option type, used for handling partial functions and optional values, and provides a collection of common combinators.
The type, the Option
exception and the functions getOpt
, valOf
and isSome
are available in the top-level environment.
Synopsis
signature OPTION
structure Option
: OPTION
Interface
datatype 'a option = NONE | SOME of 'a
exception Option
val getOpt : ('a option * 'a) -> 'a
val isSome : 'a option -> bool
val valOf : 'a option -> 'a
val filter : ('a -> bool) -> 'a -> 'a option
val join : 'a option option -> 'a option
val map : ('a -> 'b) -> 'a option -> 'b option
val mapPartial : ('a -> 'b option) -> 'a option -> 'b option
val compose : (('a -> 'b) * ('c -> 'a option)) -> 'c -> 'b option
val composePartial : (('a -> 'b option) * ('c -> 'a option)) -> 'c -> 'b option
Description
-
datatype 'a option
-
The type option provides a distinction between some value and no value, and is often used for representing the result of partially defined functions. It can be viewed as a typed version of the C convention of returning a NULL pointer to indicate no value.
-
exception Option
-
-
getOpt (opt, a)
-
returns
v
if opt isSOME v
; otherwise returns a.
-
isSome opt
-
returns
true
if opt isSOME v
; otherwise returnsfalse
.
-
valOf opt
-
returns
v
if opt isSOME v
; otherwise raises Option.
-
filter f a
-
returns
SOME a
iff a
is true andNONE
otherwise.
-
join opt
-
maps
NONE
toNONE
andSOME v
tov
.
-
map f opt
-
maps
NONE
toNONE
andSOME v
toSOME (f v)
.
-
mapPartial f opt
-
maps
NONE
toNONE
andSOME v
tof v
. The expressionmapPartial f
is equivalent tojoin o (map f)
.
-
compose (f, g) a
-
returns
NONE
ifg a
isNONE
; otherwise, ifg a
isSOME v
, it returnsSOME (f v)
. Thus, thecompose
function composes f with the partial function g, to produce another partial function. The expressioncompose (f, g)
is equivalent to(map f) o g
.
-
composePartial (f, g) a
-
returns
NONE
ifg a
isNONE
; otherwise, ifg a
isSOME v
, it returnsf v
. Thus, thecomposePartial
function composes the two partial functions f and g, to produce another partial function. The expressioncomposePartial (f, g)
is equivalent to(mapPartial f) o g
.
Discussion
Note that adding val unit = SOME
to the functions map
and join
makes the type constructor option
into a monad ([CITE]Wadler/, Section 7.2).