2009/07/04

lambda

今日の Shibuya.lisp の Shiro さんの話にもでてきたけど lambda の表記。慣れの問題かもしれないが、lambda と素直に書くのが一番読みやすい気がする。うぅむ。

(deftest test-^ ()
(is (equal '((2) (3) (4)) (mapcar (^ list (1+ _)) '(1 2 3))))
(is (equal '(1 4 9) (mapcar (^ * _ _) '(1 2 3))))
(is (equal '((1 a "A") (2 b "B"))
(mapcar (^ list _z _y _x) '("A" "B") '(a b) '(1 2))))
(is (equal '(1 2 3)
(funcall (^ identity _rest) 1 2 3)))
(is (equal '(2 1 3 4)
(funcall (^ apply #'list _b _a _rest) 1 2 3 4)))
(is (equal "a"
(with-output-to-string (*standard-output*)
(funcall (^ princ _) #\a))))
(is (equal "cba"
(with-output-to-string (*standard-output*)
(funcall (^ (princ _z) (princ _y) (princ _x)) #\a #\b #\c)))))

(deftest |test-{}| ()
(is (equal '((2) (3) (4)) (mapcar {list (1+ _)} '(1 2 3))))
(is (equal '(1 4 9) (mapcar {* _ _} '(1 2 3))))
(is (equal '((1 a "A") (2 b "B"))
(mapcar {list _z _y _x} '("A" "B") '(a b) '(1 2))))
(is (equal '(1 2 3)
(funcall {identity _rest} 1 2 3)))
(is (equal '(2 1 3 4)
(funcall {apply #'list _b _a _rest} 1 2 3 4)))
(is (equal "a"
(with-output-to-string (*standard-output*)
(funcall {princ _} #\a))))
(is (equal "abc"
(with-output-to-string (*standard-output*)
(funcall {(princ _x) (princ _y) (princ _z)} #\a #\b #\c)))))

(deftest test-lambda ()
(is (equal '((2) (3) (4)) (mapcar (lambda (x) (list (1+ x))) '(1 2 3))))
(is (equal '(1 4 9) (mapcar (lambda (x) (* x x)) '(1 2 3))))
(is (equal '((1 a "A") (2 b "B"))
(mapcar (lambda (x y z) (list z y x)) '("A" "B") '(a b) '(1 2))))
(is (equal '(1 2 3)
(funcall (lambda (&rest rest) (identity rest)) 1 2 3)))
(is (equal '(2 1 3 4)
(funcall (lambda (a b &rest rest)
(apply #'list b a rest)) 1 2 3 4)))
(is (equal "a"
(with-output-to-string (*standard-output*)
(funcall (lambda (x) (princ x)) #\a))))
(is (equal "cba"
(with-output-to-string (*standard-output*)
(funcall (lambda (x y z)
(princ z) (princ y) (princ x)) #\a #\b #\c)))))

0 件のコメント: