scheme的宏

来源:互联网 发布:sql复合主键3个 编辑:程序博客网 时间:2024/06/06 15:04

scheme的宏主要用于自定义语法结构(如while,for等);

;;;define while sentence(define-syntax while                (syntax-rules ()                 ((while conz doing ...)                  (let loop ()                    (if conz                        (begin doing ... (loop)))))))(let ((x 10))  (while (> x 0)    (display "hello")    (newline)    (set! x (- x 1))))
(define (isPrime2 n)             ;判断n是否为素数  (let ((a #t)(b #t)(i 2)(c (sqrt n)))    (while (and a b)           (set! a (<= i c))           (set! b (not (zero? (modulo n i))))           (set! i (+ i 1)))    b))(define (nextPrime2 n)     ;求n以后的下一个素数  (let ((i n))    (while (not (isPrime2 i))           (set! i (+ i 1)))    i))(time (nextPrime2 30000000000000007))


另外,一般函数使用传值调用,但有些函数要使用传引用调用(如实现swap),

类似C指针,这时需要使用宏实现:

(define-syntax swap   ; (swap a b) 交换a和b的值               (syntax-rules ()                   ((swap a b)                    (let ((c a))                        (set! a b) (set! b c))))


0 0