More Related Content Similar to Gaucheでマクロを書こう Similar to Gaucheでマクロを書こう (20) More from Hideaki Nagamine More from Hideaki Nagamine (9) Gaucheでマクロを書こう16. IF文がある
(if (> 2 1)
(print “2 is larger than 1”)
(print “1 is equal or larger than 2”))
33. FOR文をどう展開するか
(for (i 1 10)
(print i)
(print (* 2 i))
(for-each
(lambda (i)
(print i)
(print (* 2 i))
(nanika 1 10))
35. FORマクロの実装
(define (range from to)
(if (>= from to)
(list from)
(cons from (range (+ 1 from) to))))
(define-syntax for
(syntax-rules ()
((_ (i a b) body ...)
(for-each (lambda (i) body ...)
(range a b)))))
49. FOR文(二訂)
(define-macro (for bind . body)
(let ((i (car bind))
(from (cadr bind))
(to (caddr bind)))
`(let loop ((,i ,from))
(if (>= ,i ,to)
(begin ,@body)
(begin ,@body (loop (+ 1 ,i)))))))
57. 練習問題
(define x 20)
(define y 30)
`(,(+ x y) (+ x y) (+ x ,y) ,@(cons `(,x ,y) (+ x y)))
;=> (50 (+ x y) (+ x 30) (20 30) . 50)
59. FOR文(二訂)
(define-macro (for bind . body)
(let ((i (car bind))
(from (cadr bind))
(to (caddr bind)))
`(let loop ((,i ,from))
(if (>= ,i ,to)
(begin ,@body)
(begin ,@body (loop (+ 1 ,i)))))))
62. どこが良くない?
(define-macro (for bind . body)
(let ((i (car bind))
(from (cadr bind))
(to (caddr bind)))
`(let loop ((,i ,from))
(if (>= ,i ,to)
(begin ,@body)
(begin ,@body (loop (+ 1 ,i)))))))
63. どこが良くない?
(define-macro (for bind . body)
(let ((i (car bind))
(from (cadr bind))
(to (caddr bind)))
`(let loop ((,i ,from))
(if (>= ,i ,to)
(begin ,@body)
(begin ,@body (loop (+ 1 ,i)))))))
66. YOKUNAI
(let loop ((loop 1))
(if (>= loop 5)
(begin (print loop))
(begin (print loop) (loop (+ 1 loop)))))
invalid application: (1 2)
67. 良くない解決策
(define-macro (for bind . body)
(let ((i (car bind))
(from (cadr bind))
(to (caddr bind)))
`(let asjdiwoqwe ((,i ,from))
(if (>= ,i ,to)
(begin ,@body)
(begin ,@body (asjdiwoqwe (+ 1 ,i)))))))
71. FOR文(三訂)
(define-macro (for bind . body)
(let ((i (car bind))
(from (cadr bind))
(to (caddr bind))
(loop (gensym)))
`(let ,loop ((,i ,from))
(if (>= ,i ,to)
(begin ,@body)
(begin ,@body (,loop (+ 1 ,i)))))))
79. アリティの固定
(define 1- (cut - <> 1))
(define (repeat n fn)
(let loop ((m n) (x '()))
(if (= m 0)
x
(loop (1- m) (cons (fn) x)))))
(define-macro (*-ary n fn)
(let ((args (repeat n gensym)))
`(lambda ,args (,fn ,@args))))
; (arity (*-ary 4 +))
; => 4