Skip to content

Instantly share code, notes, and snippets.

@chuntaro
Created July 9, 2023 11:00
Show Gist options
  • Select an option

  • Save chuntaro/a55983391f5da406ebb3247d4566deb4 to your computer and use it in GitHub Desktop.

Select an option

Save chuntaro/a55983391f5da406ebb3247d4566deb4 to your computer and use it in GitHub Desktop.
Emacs で with-cache を実装してみた
;;; -*- lexical-binding: t; -*-
;; 括弧への異常な愛情 (https://www.slideshare.net/m2ym/common-lisp-9838434)
;; からの引用
(require 'cl-lib)
(defmacro with-cache (key &rest body)
(declare (indent 1))
(cl-once-only (key)
(cl-with-gensyms (cache)
`(let ((,cache (cl-load-time-value
(make-hash-table :test 'equal))))
(or (gethash ,key ,cache)
(setf (gethash ,key ,cache)
(cl-locally ,@body)))))))
(defun fib (n)
(if (< n 2)
n
(+ (fib (- n 2)) (fib (1- n)))))
(benchmark-progn
(print (fib 38)))
(defun fib (n)
(with-cache n
(if (< n 2)
n
(+ (fib (- n 2)) (fib (1- n))))))
(benchmark-progn
(print (fib 38)))
;; 実行方法
;;
;; $ emacs --batch -f batch-byte-compile test-with-cache.el
;; $ emacs --script test-with-cache.elc
;; 実行結果
;;
;; 39088169
;;
;; Elapsed time: 4.469694s
;;
;; 39088169
;;
;; Elapsed time: 0.000939s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment