Skip to content

Instantly share code, notes, and snippets.

@geekrelief
Last active December 10, 2021 20:38
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 geekrelief/d786f01f89d20090f30e4d7ef2325a8e to your computer and use it in GitHub Desktop.
Save geekrelief/d786f01f89d20090f30e4d7ef2325a8e to your computer and use it in GitHub Desktop.
Apply / Splat for Nim
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