Skip to content

Instantly share code, notes, and snippets.

@ishowta
Last active February 25, 2020 11:43
Show Gist options
  • Save ishowta/fbcc9b1bbb9d1c06184dbd7cc2f28ecd to your computer and use it in GitHub Desktop.
Save ishowta/fbcc9b1bbb9d1c06184dbd7cc2f28ecd to your computer and use it in GitHub Desktop.
DI by macro
import macros, sugar, sequtils
import rationals
proc `//`[T: SomeInteger](num, den: T): Rational[T] = initRational(num, den)
proc `//`[T: not SomeInteger](num, den: T): auto = num / den
proc genReplacer(fromNode, toNode: NimNode): auto =
proc replacer(node: NimNode):NimNode =
if node.len == 0:
if node.kind == nnkIdent and node == fromNode:
return toNode
else:
return node
let newNode = copyNimNode(node)
newNode.add node.mapIt(replacer(it))
return newNode
return replacer
macro Rational(field: untyped):untyped = genReplacer(ident"/", ident"//")(field)
block:
echo 1 / 2
echo 1.0 / 2.0
Rational:
echo 1 / 2
echo 1.0 / 2.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment