## std.options: Optional types. ## This module is imported by default. use std.format ## The `Option` type. ## A type that represents either the presence or absence of a value. pub type Option[T] = union Some(T) None ## Syntactic sugar for optional type declarations. pub macro ?(T: type) = quote Option[`T`] ## Directly accesses the inner value. Throws an exception if None. pub func ![T](self: T?): T = if self of Some(x) then x else raise "empty" ## Indirect access. Propagates `None`. pub macro ?[T](self: T?) = quote match `self` of Some(x) then x of None then return None ## Checks if a type is present within an `Option` type. pub func is_some[T](self: T?): bool = self of Some(_) ## Checks if a type is not present within an `Option` type. pub func is_none[T](self: T?): bool = self of None ## Converts an `Option[T]` to a `Result[T, E]` given a user-provided error. pub func err[T, E](self: T?, error: E): Result[T, E] = if self of Some(x) then Okay(x) else Error(error) ## Applies a function to `T`, if it exists. pub func map[T, U](self: T?, fn: T -> U): U? = if self of Some(x) then Some(fn(x)) else None ## Converts `T` to a `None`, if `fn` returns false and it exists. pub func filter[T](self: T?, fn: T -> bool): T? = if self of Some(x) and fn(x) then Some(x) else None ## Applies a function to T, if it exists. Equivalent to `self.map(fn).flatten`. pub func flatmap[T, U](self: T?, fn: T -> U?): U? = if self of Some(x) then fn(x) else None ## Converts from Option[Option[T]] to Option[T]. pub func flatten[T](self: T??): T? = if self of Some(Some(x)) then Some(x) else None ## Returns the inner value or a default. pub func get_or[T](self: T?, default: T): T = if self of Some(x) then x else default ## Overloads the `==` operation for use on Options. pub func ==[T](a, b: T?): bool = if (a, b) of (Some(x), Some(y)) then x == y else false ## Overloads the `str()` function for use on Options. pub func str[T: Display](self: T?): str = if self of Some(x) then "Some({})".fmt(x.str) else "None" examples let x = Some(42) if x of Some(y) then assert x! == y # references: # https://nim-lang.github.io/Nim/options.html # https://doc.rust-lang.org/std/option/enum.Option.html