Skip to content

Instantly share code, notes, and snippets.

@elcritch
Created June 12, 2023 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elcritch/8e454c3269ba6d6a62793ddfab30da66 to your computer and use it in GitHub Desktop.
Save elcritch/8e454c3269ba6d6a62793ddfab30da66 to your computer and use it in GitHub Desktop.
Experiment with Nim Pattern Matching Syntax
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