Drkcore

21 01 2009 lisp Tweet

Common Lispで遅延評価

On Lisp15章。マクロで遅延評価を実装

(defconstant unforced (gensym))
(defstruct delay forced closure)

(defmacro delay (expr)
  (let ((self (gensym)))
    `(let ((,self (make-delay :forced unforced)))
       (setf (delay-closure ,self)
         #'(lambda () (setf (delay-forced ,self) ,expr))) ,self)))

(defun force(x)
  (if (delay-p x)
      (if (eq (delay-forced x) unforced)
          (funcall (delay-closure x))
          (delay-forced x))
      x))

これを使う場合

(let ((x 2))
(setq d (delay (1+ x))))

そのままでは評価されない

 d
 #S(DELAY :FORCED #:G748 :CLOSURE #<CLOSURE (LAMBDA #) {12234AF5}>)

forceしてやる

(force d)
3

ProductName On Lisp
ポール グレアム,野田 開
オーム社 / ¥ 3,990 ()
通常24時間以内に発送

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021