Hatena::Groupcadr

kozima の日記

2010-01-07

special variable の変な使い方

23:33

関数の仮引数に special variable を使うとこんなことができるんですね。

(defun foo (*standard-output*)
  (format t "hoge"))

(with-output-to-string (s) (foo s))
;=> "hoge"

可読性が低くなりそうだしゴルフにも使えそうにありません。

eval-print-last-sexp の出力を逆引き CL 書式に

| 00:01

改造してみた。わりと強引だし,うまくいかない例は作ればたくさんありますが。

(defun mylib-eval-last-sexp-to-string ()
  (let ((res (make-string-output-stream))
        (out (make-string-output-stream)))
    (let ((*standard-output* out))
      (eval-last-sexp res))
    (values (get-output-stream-string res)
            (get-output-stream-string out))))

(defun mylib-eval-print-last-sexp ()
  (interactive "*")
  (multiple-value-bind (result output)
      (mylib-eval-last-sexp-to-string)
    (flet ((format-output (string stream)
             (when (plusp (length string))
               (format stream "~&~{;-> ~A~%~@{;   ~A~%~}~}"
                       (split-string string "\n" t))))
           (format-result (string stream)
             (if (plusp (length string))
                 (format stream "~&~{;=> ~A~%~@{;   ~A~%~}~}"
                         (split-string string "\n" t))
               (format stream "~&;=> No value~%"))))
      (with-output-to-selected-buffer
        (format-output output *standard-output*)
        (format-result result *standard-output*)))))