2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

無名関数(lambda)を簡潔にするリードマクロ

Last updated at Posted at 2015-10-08

On Lispとか有名な本に載っていそう

引数は1つしか取れませんが引数を返す無名関数など短い無名関数を書くときに役立つと思います.

(defun special-lambda-expression (stream char &optional (arg (gensym)))
  (let* ((el (read stream))
         (rec (labels ((self (x)
                         (cond
                           ((consp x) (mapcar #'self x))
                           ((symbolp x) (if (eq x '_) arg x))
                           (t x))))
                #'self))
         (body (funcall rec el)))
    `(lambda (,arg) ,body)))
(set-macro-character #\! #'special-lambda-expression)

実行例

!_ ; -> (lambda (#G:1501) #G:1501)
!(* 2 _) ; -> (lambda (#G:1502) (* 2 #G:1502))
!(* 2 (+ 1 _)) ; -> (lambda (#G:1503) (* 2 (+ 1 #G:1503)))

多引数対応に拡張したほうが実用的そうですね.

2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?