Skip to content

Instantly share code, notes, and snippets.

@mratsim
Created April 24, 2018 06:11
Show Gist options
  • Save mratsim/5fed4b3c1f2f4ea613d155548101a783 to your computer and use it in GitHub Desktop.
Save mratsim/5fed4b3c1f2f4ea613d155548101a783 to your computer and use it in GitHub Desktop.
macro myzip(x: ForLoopStmt): untyped =
x.expectKind nnkForStmt
result = newStmtList()
echo x.treeRepr
echo "\n##################"
# Count the number of idents:
var ident_count = 1
while x[ident_count + 1].kind == nnkIdent:
inc ident_count
assert ident_count == 1 # no tuple deconstruction yet ...
# Check the smallest seq:
x[ident_count].expectKind nnkCall
let last_container = x[ident_count].len
var len = high(int)
for i in 1 ..< last_container:
len = min(len, x[ident_count][i].len)
# Create a new for loop iteration container
var c = nnkBracket.newTree()
for j in 0 ..< len: # iterate over the containers
var p = nnkPar.newTree()
for i in 1 ..< last_container: # iterate over the index
p.add x[ident_count][i][j]
c.add p
# Add the iteration variable
var newFor = newTree(nnkForStmt)
for i in 0 ..< ident_count:
newFor.add x[i]
# Add the new containers
newFor.add c
# Add the body
newFor.add x[^1]
# Finalize
result.add newFor
for a in myZip([1, 2, 3, 11, 14], [4, 5, 6, 11, 12, 15], [7, 8, 9, 13, 16]):
echo a
# Promising with a few caveats
# Questions:
# - this doesn't work with variables like "x" instead of [1, 2, 3, 11, 14]
# - this works only if the containers have all the same type, as I'm mixing the arrays
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment