Skip to content

Instantly share code, notes, and snippets.

@Araq
Created August 15, 2018 18:43
Show Gist options
  • Save Araq/169d1e24b2b996d024a780ef6a4e6c09 to your computer and use it in GitHub Desktop.
Save Araq/169d1e24b2b996d024a780ef6a4e6c09 to your computer and use it in GitHub Desktop.
{.experimental: "caseStmtMacros".}
import macros
macro match(n: tuple): untyped =
result = newTree(nnkIfStmt)
let selector = n[0]
for i in 1 ..< n.len:
let it = n[i]
case it.kind
of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr:
result.add it
of nnkOfBranch:
for j in 0..it.len-2:
let cond = newCall("==", selector, it[j])
result.add newTree(nnkElifBranch, cond, it[^1])
else:
error "'match' cannot handle this node", it
echo repr result
case ("foo", 78)
of ("foo", 78): echo "yes"
of ("bar", 88): echo "no"
else: discard
@kaushalmodi
Copy link

But supporting _ placeholder is very useful, would be nice to support it

++++1

@timotheecour
Copy link

=> moving discussion to somwhere more visible in https://github.com/nim-lang/Nim/issues/8649

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment