首页 > 解决方案 > Common Lisp 中重复的 case 语句

问题描述

这里必须有更好的方法来做到这一点,对吧?

(format t "Enter your age: ~%")

(defun age-case (age)
  (case age
    (1 (format t "You belong in Kindergarden~%"))
    (2 (format t "You belong in Kindergarden~%"))
    (3 (format t "You belong in Kindergarden~%"))
    (4 (format t "You belong in Kindergarden~%"))
    (5 (format t "You belong in Preschool~%"))
    (6 (format t "Elementary school ~%"))
    (t (format t "Somewhere else"))))

(defvar *age* (read))

(age-case *age*)

在 Python 中,我会为此使用案例 1..4,在 C++、Java 和 co 中。我可能会使用一个falltrough switch case,其中我省略了案例1到3的中断。在没有代码重复的情况下,是否有一个巧妙的小技巧可以在clisp中做到这一点?

标签: common-lisp

解决方案


另一种选择是使用类型说明符:

CL-USER > (let ((age 6))
            (typecase age
              ((integer 1 4) 'one-to-four)   ; integers from 1 to 4
              ((eql 5)       'five)
              ((eql 6)       'six)
              (t             'something-else)))
SIX

推荐阅读