Comment detail

法演算 (Nested Flatten)

This comment is reply for 4930 shiro: アルゴリズムよりも、言語ごとのイディオム...(法演算). Go to thread root.

一方、式を外部から与えたいなら、+, -, * の束縛がmodular arithmeticに置き換わったようなモジュールを用意してその中でevalするという手が使えます。

 gosh> (eval-modular 10 '(+ 2 9))
 1
 gosh> (eval-modular 10 '(- 2 9))
 3
 gosh> (eval-modular 10 '(* 2 9))
 8
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
(define (make-modular op m)
  (lambda xs
    (modulo (apply op (map (cut modulo <> m) xs)) m)))

(define (make-modular-module m)
  (let1 mod (make-module #f)
    (eval `(define + ,(make-modular + m)) mod)
    (eval `(define - ,(make-modular - m)) mod)
    (eval `(define * ,(make-modular * m)) mod)
    mod))

(define (eval-modular m expr)
  (eval expr (make-modular-module m)))

Index

Feed

Other

Link

Pathtraq

loading...