aboutsummaryrefslogtreecommitdiff
path: root/std/default/options.pk
diff options
context:
space:
mode:
Diffstat (limited to 'std/default/options.pk')
-rw-r--r--std/default/options.pk24
1 files changed, 15 insertions, 9 deletions
diff --git a/std/default/options.pk b/std/default/options.pk
index 397a8f3..fb696ba 100644
--- a/std/default/options.pk
+++ b/std/default/options.pk
@@ -1,12 +1,12 @@
## std/options: Optional types.
## This module is imported by default.
-import std/format
+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
+ Some(T)
None
## Checks if a type is present within an `Option` type.
@@ -43,7 +43,7 @@ pub func flatmap[T, U](self: Option[T], fn: T -> Option[U]): Option[U] =
else:
None
## Converts from Option[Option[T]] to Option[T].
-pub func flatten[T](self: Option[Option[T]]): Option[T] = # todo: better name?
+pub func flatten[T](self: Option[Option[T]]): Option[T] =
match self
of Some(Some(x)):
Some(x)
@@ -55,19 +55,25 @@ pub func get_or[T](self: Option[T], default: T): T =
if self of Some(x): x
else: default
## Directly accesses the inner value. Throws an exception if None.
-pub yeet func `!`[T](self: Option[T]): T =
+pub func ![T](self: Option[T]): T =
if self of Some(x): x
else: raise Exception # todo: syntax??
## Indirect access. Propagates `None`.
-pub macro `?`[T](self: Option[T]) =
+## Parsed by compiler magic.
+pub macro ?[T](self: Option[T]) =
quote:
- match self
+ match `self`
of Some(x): x
of None: return None
+## Syntactic sugar for optional type declarations.
+pub macro ?(T: type) =
+ quote:
+ Option[`T`]
+
## Overloads the `==` operation for use on Options.
-pub func `==`[T](a, b: Option[T]): bool =
+pub func ==[T](a, b: Option[T]): bool =
match (a, b)
of (Some(x), Some(y)):
x == y
@@ -77,9 +83,9 @@ pub func `==`[T](a, b: Option[T]): bool =
## Overloads the `str()` function for use on Options.
pub func str[T](self: Option[T]): str =
if self of Some(x):
- fmt("some({})", x.str)
+ fmt("Some({})", x.str)
else:
- "none"
+ "None"
examples:
let x = Some(42)