lisp 裡的條件判斷

babyyellow發表於2012-12-25

if    , cond , case

and  , or  也可以作為判斷的一種方式


其中case  是的比對是基於eq  , 所以業務上應該儘量避免基於字串的對比。

示例:

CL-USER> (if (oddp 5 )
         'odd-number
         'even-number)
ODD-NUMBER
CL-USER> (if (oddp 6 )
         'odd-number
         'even-number)
EVEN-NUMBER

CL-USER> (defun pudding-eater (person)
       (case person
         ((henry) (setf *arch-enemy* 'henry)
                  '(curse you lisp alien - you ate my pudding))
         ((johnny) (setf *arch-enemy* 'johnny)
                   '(i hope you choked on my pudding johnny))
         (otherwise '(why you eat my pudding stranger ?))))
STYLE-WARNING: redefining COMMON-LISP-USER::PUDDING-EATER in DEFUN
PUDDING-EATER
CL-USER> (pudding-eater 'johnny)
(I HOPE YOU CHOKED ON MY PUDDING JOHNNY)
CL-USER> (pudding-eater 'henry)
(CURSE YOU LISP ALIEN - YOU ATE MY PUDDING)



CL-USER> (defun pudding-eater (person)
       (case person
         ((henry) (setf *arch-enemy* 'henry)
                  '(curse you lisp alien - you ate my pudding))
         ((johnny) (setf *arch-enemy* 'johnny)
                   '(i hope you choked on my pudding johnny))
         (otherwise '(why you eat my pudding stranger ?))))
STYLE-WARNING: redefining COMMON-LISP-USER::PUDDING-EATER in DEFUN
PUDDING-EATER
CL-USER> (pudding-eater 'johnny)
(I HOPE YOU CHOKED ON MY PUDDING JOHNNY)
CL-USER> (pudding-eater 'henry)
(CURSE YOU LISP ALIEN - YOU ATE MY PUDDING)


CL-USER> (or (oddp 5 ) (oddp 7 ) (oddp 11) (oddp 3))
T
CL-USER> (or (oddp 5 ) (oddp 7 ) (oddp 11) (oddp 3))
T
CL-USER> (and  (oddp 5 ) (oddp 7 ) (oddp 11) (oddp 3))
T
CL-USER>

CL-USER> *is-it-even*
NIL
CL-USER> (defparameter *is-it-even* nil)
*IS-IT-EVEN*
CL-USER> *is-it-even*
NIL
CL-USER> (or (oddp 4 ) (setf *is-it-even* t))
T
CL-USER> *is-it-even*
T
CL-USER> (and (oddp 3) (setf *is-it-even* nil))
NIL
CL-USER> *is-it-even*
NIL
CL-USER> (setf *is-it-even* t)
T
CL-USER> (and (oddp 4) (setf *is-it-even* nil))
NIL
CL-USER> *is-it-even*
T





來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/133735/viewspace-751620/,如需轉載,請註明出處,否則將追究法律責任。

相關文章