Lisp:遇到条件问题

Lisp: Having Trouble with Conditionals

大家好,我刚开始在我的大学学习 Lisp,但是教授非常穷,而且他自己似乎不懂这门语言,所以我求助于大家。我在 Java 方面非常有经验,并且在将 Java 的条件与 Lisp 相关联时遇到了麻烦。这是我要解决的问题。

"Write a function which takes the age of the passenger and the amount of airfare between two cities. If the child is less than two the airfare is 0, between two and five it is 60 percent of the full fare. If the child is five or older they full fare."

这是我的解决方案,但我觉得这是低效的。

(defun young-child(x y)
        (cond
          ((< x 2) 0)
          ((= x 2) (* y .6))
          ((= x 3) (* y .6))
          ((= x 4) (* y .6))
          ((= x 5) (* y .6))
          ((> x 5) y)))

现在 Java 我只想说

if (x >= 2 && x =< 5) {
  return y*.6
}
else if (x < 2) {
  return 0;
}
else {
  return y;
}

我想问的是:有没有更好的方法来编写这个 Lisp 条件语句?如果我必须检查更大范围的年龄,那么使用这种方法的代码会变得非常乏味。在 Lisp 中有没有一种方法可以像我在 Java 中所做的那样在一个 if 语句中检查 2 个条件?非常感谢您查看此代码以及任何未来的回复!

Lisp 有一个 AND 运算符,可用于组合多个条件。

(defun young-child (x y)
  (cond ((and (>= x 2) (<= x 5)) (* y .6))
        ((< x 2) 0)
        (t y)))

您也可以通过单个函数调用 (<= 2 x 5)(>= 5 x 2) 来测试 x 是否介于 25 之间。

但是如果先测试(< x 2),之后就不需要再测试是否(>= x 2),因为条件是按给定的顺序测试的。

(defun young-child (x y)
  (cond ((< x 2) 0)
        ((<= x 5) (* y .6))
        (t y)))

也可以:

(defun young-child (age fare) 
  (* (con ((< age 2) 0) 
          ((< age 5) .6)
          (t 1)) 
     fare)

函数式编程使之成为可能:) .