Created
June 12, 2023 23:09
-
-
Save elcritch/8e454c3269ba6d6a62793ddfab30da66 to your computer and use it in GitHub Desktop.
Experiment with Nim Pattern Matching Syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import macros | |
type | |
EitherKind {.pure.} = enum | |
Some, None | |
Either[T] = object | |
case kind: EitherKind | |
of Some: | |
val: T | |
of None: | |
discard | |
proc `==`*[T](a: Either[T]; b: Either[T]): bool = | |
if a.kind == b.kind: | |
case a.kind | |
of Some: | |
return a.val == b.val | |
of None: | |
return true | |
else: | |
return false | |
proc some*[T](val: T): Either[T] = Either[T](kind: Some, val: val) | |
proc none*[T](val: T): Either[T] = Either[T](kind: None) | |
macro `as`*(a: typed, b: untyped): untyped = | |
let | |
tpinst = getTypeInst(a) | |
tpimpl = getTypeImpl(a) | |
kind = b[0] | |
name = b[1] | |
result = quote do: | |
let res = `a`.kind == `kind` | |
let `name` {.inject.}: int = if res: `a`.val | |
else: default(`a`.val.type) | |
res | |
block: | |
let x = some 3 | |
if x as Some(y): | |
echo "huzzah! x: ", x, " y: ", y | |
else: | |
echo "sad day!" | |
block: | |
let x = none 3 | |
if x as Some(y): | |
echo "huzzah! x: ", x, " y: ", y | |
else: | |
echo "sad day!" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment