Last active
December 10, 2021 20:38
-
-
Save geekrelief/d786f01f89d20090f30e4d7ef2325a8e to your computer and use it in GitHub Desktop.
Apply / Splat for Nim
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 | |
proc mysum(a, b, c, d:int) = | |
echo a + b + c + d | |
macro apply(fun, args: typed): untyped = | |
result = newCall(fun) | |
var funArgLen = getType(fun).len - 2 | |
case args.kind: | |
of nnkBracket: | |
for a in args: | |
result.add a | |
of nnkPrefix: | |
if args[0].repr == "@": | |
for a in args[1]: | |
result.add a | |
of nnkTupleConstr: | |
for a in args: | |
result.add a | |
of nnkSym: | |
for i in 0..<funArgLen: | |
var b = newTree(nnkBracketExpr) | |
b.add args | |
b.add newLit(i) | |
result.add b | |
else: | |
#echo args.astGenRepr | |
discard | |
let myarr = [1, 2, 3, 4] | |
mysum.apply(myarr) | |
mysum.apply([5, 6, 7, 8]) | |
mysum.apply(@[9, 10, 11, 12]) | |
let myseq = @[1, 2, 3, 4] | |
mysum.apply(myseq) | |
mysum.apply((1, 2, 3, 4)) | |
let mytup = (5, 6, 7, 8) | |
mysum.apply(mytup) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment