Skip to content

Instantly share code, notes, and snippets.

@SaitoAtsushi
Created October 30, 2018 15:38
Show Gist options
  • Save SaitoAtsushi/264a4b5546535c910cc15191f383a6c1 to your computer and use it in GitHub Desktop.
Save SaitoAtsushi/264a4b5546535c910cc15191f383a6c1 to your computer and use it in GitHub Desktop.
効率的に平均を計算するマクロ
#!r6rs
(library (average)
(export average)
(import (rnrs))
(define (%average . args)
(/ (apply + args)
(length args)))
(define-syntax average
(make-variable-transformer
(lambda(ctx)
(syntax-case ctx ()
((_ args ...)
#'(letrec-syntax
((% (lambda(ctx2)
(syntax-case ctx2 ()
((_ sum ())
#`(/ sum #,(+ (begin 'args 1) ...)))
((_ sum (rt (... ...)))
#`(/ (+ sum rt (... ...))
#,(+ (begin 'args 1) ...)))
((_ sum (rt (... ...)) r0 r1 (... ...))
(number? (syntax->datum #'r0))
#`(% #,(+ (syntax->datum #'r0)
(syntax->datum #'sum))
(rt (... ...)) r1 (... ...)))
((_ sum (rt (... ...)) r0 r1 (... ...))
#'(% sum (rt (... ...) r0) r1 (... ...)))))))
(% 0 () args ...)))
(_ #'%average)))))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment