LoginSignup
3
2

More than 5 years have passed since last update.

lambda短縮マクロ

Last updated at Posted at 2012-03-16

登録記念にlisp支援。
前に書いたlambda短縮マクロ。既出?

CommonLisp
(defun deep-find (item seq &key (test #'eql))
  (if (not (null seq))
      (or (if (funcall test item (car seq))
              item
              (if (not (atom (car seq)))
                  (deep-find item (car seq) :test test)))
          (deep-find item (cdr seq) :test test))))

(defmacro >str (&body body)
  `(write-to-string ,@body))
(defmacro >sym (str &optional package)
  `(intern ,str ,package))
(defmacro str+ (&rest b)
  `(concatenate 'string ,@b))

(set-macro-character #\] (get-macro-character #\)))
(set-dispatch-macro-character #\# #\[
  #'(lambda (stream char1 char2)
      (let ((body (read-delimited-list #\] stream t)))
        (if (deep-find '_ body)
            `(function (lambda (_) ,body))
            `(function
              (lambda
                  ,(nreverse
                    (do ((i 0 (1+ i)) (var nil))
                        ((> i 9) var)
                      (if (deep-find (>sym (str+ "_" (>str i)) *package*) body)
                          (setq var (cons (>sym (str+ "_" (>str i)) *package*) var)))))
               ,body))))))

テスト

CommonLisp
;; #[+ 1 2] 
;;  => #'(lambda () (+ 1 2))
;;
;; #[+ _ 1] 
;;  => #'(lambda (_) (+ _ 1))
;;
;; #[if (< _0 10) (+ _1 2) (+ (- 100 _0) _2)] 
;;  => #'(lambda (_0 _1 _2) (if (< _0 10) (+ _1 2) (+ (- 100 _0) _2)))

> (funcall #[+ 10 100])
; 110
> (funcall #[+ _ 100] 1)
; 101
> (mapcar #[list _0 _1 _2] '(1 2 3) '(4 5 6) '(7 8 9))
;((1 4 7) (2 5 8) (3 6 9))
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2