如何将此功能转换为宏?

时间:2011-08-20 11:27:04

标签: macros scheme

我很难理解Scheme的新宏系统。在路径的某个地方,我开始首先将“宏”作为函数编写,然后将其作为宏应用。

所以我的任务是改变以下结构:

;; highlight-rules: rule id, color and the regexp matches
(define highlight-rules
  `((important   ,(with-esc "[1;33m") ("foo"
                                       "bob"))
    (unimportant ,(with-esc "[1;30m") ("case of unimport"))
    (urgent      ,(with-esc "[1;31m") ("urgents"))))

进入这种cond系列,匹配字符串编译为正则表达式:

;; just an example. `line` is an argument bound by the function application
(cond
  ((string-match (regexp ".*sudo:session.*") line)
     (with-color *important* line))
  (else line))

我写了一个似乎可以解决这个问题的函数:

;; (cdar highlight-rules) -> (colorstring   list-of-rules)
(define (parse-highlight-rules rules)
  ;; aux function to do one 'class' of patterns
  (define (class-of-rules colorstr rulelist)
    (map (lambda (rule)
        `((string-match ,(regexp rule)) (with-color ,colorstr line)))
        rulelist))
  (define (do-loop accumulator rules)
    (let* ((highlight-group (cdar rules))
           (colorstr        (car highlight-group))
           (grouprules      (cadr highlight-group))
           (acc*            (append (class-of-rules colorstr grouprules) accumulator))
           (rest            (cdr rules)))
    (if (null? rest)
        acc*
        (do-loop acc* rest))))
  ; wrap the list in cond.
  `(apply cond ,(do-loop '() rules)))

使用给定的highlight-rules函数返回正确的列表(除了应用apply - 在clojure中,将使用拼接):

CSI> (parse-highlight-rules highlight-rules)
(apply cond (((string-match #<regexp>) (with-color "\x1b[1;31m" line))
            ((string-match #<regexp>) (with-color "\x1b[1;30m" line))
            ((string-match #<regexp>) (with-color #0="\x1b[1;33m" line))
            ((string-match #<regexp>) (with-color #0# line))))

但是如何处理呢?我已经坚持了一段时间。鸡计划是我的方言。

1 个答案:

答案 0 :(得分:1)

将函数转换为宏的最简单方法是使用Chicken的explicit-renaming宏工具,它与Clojure的defmacro类似(除了显式重命名宏需要一些额外的参数,可以是用于保护卫生。)

拼接的工作方式与Clojure中的拼接方式基本相同。语法为,@。因此,以下应该有效:

(define-for-syntax (parse-highlight-rules rules)
  ;; ... insert missing code here ...
  `(cond ,@(do-loop '() rules)))

(define-syntax highlight
  (er-macro-transformer
    (lambda (form rename compare)
      (parse-highlight-rules (cdr form)))))