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
@timotheecour
Copy link

timotheecour commented Aug 15, 2018

=> moved to https://github.com/nim-lang/Nim/issues/8649 (caseStmtMacros and ifStmtMacros to support C#8-like Recursive Patterns matching (Deconstruction Pattern))

@Araq
Copy link
Author

Araq commented Aug 15, 2018

Well match can rewrite the case statement in any way you see fit, it can introduce binding to locals or "don't care" symbols.

@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