optional_t
What is optional_t
A simple library for an Option[T]
. The goal is to have clear syntax and be
easy to use.
Usage
Construction
-
Some("some value")
creates anOption[string]
that has a value. -
None[string]()
creates a value of the same type, but without a value. -
var foo: Option[string]
has a value ofNone[String]()
. In other words,foo == None[String]()
. -
Some[string](nil)
is invalid: the value inside aSome[ref T]
is required to never be nil. This is only validated in debug mode, the check is disabled in release mode unless assertions are enabled.
Operations
-
isNone(Option[T]): bool
-
returns
true
if theOption[T]
isNone
, otherwise returnsfalse
. -
isSome(Option[T]): bool
-
returns
not isNone(…​)
-
get(Option[T], [default: T]): T
-
Gets the value from the
Option[T]
. If theOption[T]
isNone
, it raises an exception unlessdefault
is passed, in which case it returnsdefault
. -
unsafeGet(Option[T]): T
-
Gets the value inside the
Option[T]
, behavior is undefined if it isNone
. You probably don’t need this, the C optimizer is pretty good. Worry about the humans, not the computer. -
map(Option[T], proc(T): R): R
-
If the
Option[T]
is notNone
, the passed procedure is executed with it’s value as a parameter, otherwise aNone
is returned without executing the passed procedure. -
if myOptionT: …​
-
The
if
condition evaluates totrue
if the value isSome
, otherwise it evaluates tofalse
.
$
and ==
work as expected.
Note: If optional_t.nonstrict
is imported, then all Option[T]
s are
automatically unpacked where necessary. This uses a converter, so the laziness
might lead to odd errors.