Skip to content

Instantly share code, notes, and snippets.

@planetis-m
Forked from Araq/listcomprehensions.nim
Last active October 25, 2018 19:27
Show Gist options
  • Save planetis-m/15968fb7e5ae0b414857360ac930c4e8 to your computer and use it in GitHub Desktop.
Save planetis-m/15968fb7e5ae0b414857360ac930c4e8 to your computer and use it in GitHub Desktop.
import macros, sets
macro lcSet(body): untyped =
# analyse the body, find the deepest expression 'it' and replace it via
# 'result.add it'
let res = genSym(nskVar, "lcResult")
proc t(n, res: NimNode): NimNode =
# Looks for the last statement of the last statement, etc...
case n.kind
of nnkStmtList, nnkStmtListExpr, nnkBlockStmt, nnkBlockExpr,
nnkWhileStmt,
nnkForStmt, nnkIfExpr, nnkIfStmt, nnkTryStmt, nnkCaseStmt,
nnkElifBranch, nnkElse, nnkElifExpr:
result = copyNimTree(n)
if n.len >= 1:
result[^1] = t(n[^1], res)
else:
# add checks for {k: v}, {k} here
template adder(res, n) =
res.incl n
result = getAst adder(res, n)
let v = newTree(nnkVarSection,
newTree(nnkIdentDefs, res, newEmptyNode(), newTree(nnkCall, newTree(nnkBracketExpr, bindSym"initSet",
newCall(bindSym"typeof", body)))))
result = newTree(nnkStmtListExpr, v, t(body, res), res)
echo repr result
import tables, sets
var data = {2: "bird", 5: "word"}.toTable
let x = lcSet:
for k, v in data:
if k mod 2 == 0:
k
echo x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment