Skip to content

Instantly share code, notes, and snippets.

@mashingan
Created September 11, 2017 07:17
Show Gist options
  • Save mashingan/afc9275eed4338bd8299b408399b42ae to your computer and use it in GitHub Desktop.
Save mashingan/afc9275eed4338bd8299b408399b42ae to your computer and use it in GitHub Desktop.
defining match syntax using Nim macro
import macros
macro match(head, body: untyped): untyped =
result = newNimNode nnkStmtList
var casenode = newNimNode nnkCaseStmt
casenode.add head
for node in body:
node.expectKind nnkInfix
var ofbranch: NimNode
case $node[0]
of "->": ofbranch = newNimNode nnkOfBranch
of "=>": ofbranch = newNimNode nnkElifBranch
#var ofbranch = newNimNode nnkOfBranch
for i in 1 ..< node.len:
if i != node.len - 1 or node.kind != nnkStmtList:
ofbranch.add node[i]
else:
ofbranch.add(newStmtList node[i])
casenode.add ofbranch
result.add casenode
expandMacros:
match "3":
"3" -> echo "it's 3"
"4" -> echo "it's 4"
match "3":
"3" -> echo "it's 3"
"4" -> echo "4"
match 3 in @[1, 2, 3]:
true -> echo "it's there"
false -> echo "it's not there"
match "3":
"nice" -> echo "3 is not nice"
3 in @[1, 2, 3] => echo "haha, it works"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment