Skip to content

Instantly share code, notes, and snippets.

@samth
Forked from jlongster/gist:1651726
Created January 21, 2012 14:28
Show Gist options
  • Save samth/1652932 to your computer and use it in GitHub Desktop.
Save samth/1652932 to your computer and use it in GitHub Desktop.
Macros
;; AST style:
((equal? term "cond")
(define (transform i)
(if (or (> i node.children.length)
(eq? i node.children.length))
null
(let ((n (vector-ref node.children i)))
(let ((condition (vector-ref n.children 0))
(res (ast.node ast.LIST
null
(vector-concat
(list (ast.node ast.TERM (make-symbol "begin")))
(n.children.slice 1)))))
(if (and (eq? condition.type ast.TERM)
(equal? condition.data.str "else"))
res
(ast.add_child
(ast.node ast.LIST
null
(list (ast.node ast.TERM (make-symbol "if"))
condition
res))
(transform (+ i 1))))))))
(let ((res (transform 1)))
;; maintain node links
(set! res.link node.link)
(parse res)))
;; define-macro style:
(define-macro (cond . forms)
(if (null? forms)
'#f
(let ((form (car forms)))
(if (eq? (car form) 'else)
`(begin ,@(cdr form))
`(if ,(car form)
(begin ,@(cdr form))
(cond ,@(cdr forms)))))))
;; syntax-parse style:
(define-syntax cond
(syntax-parser
[(cond) #'#f]
[(cond [(~literal else) rest ...] more ....) #'(begin rest ...)]
[(cond [tst rhs ...] more ...)
#'(if tst (begin rhs ...) (cond more ...))]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment