Last active
February 25, 2020 11:43
-
-
Save ishowta/fbcc9b1bbb9d1c06184dbd7cc2f28ecd to your computer and use it in GitHub Desktop.
DI by macro
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, 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