Warm tip: This article is reproduced from serverfault.com, please click

Lisp: Having Trouble with Conditionals

发布于 2016-01-19 20:31:43

Hey guys I am just starting to learn Lisp at my university however the professor is incredibly poor and does not seem to know the language himself so I turn to you all. I am very experienced in Java and am having trouble relating the conditionals of Java to Lisp. Here is the problem I am asked to solve.

"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."

Here is my solution that worked, but I feel like this is inefficient.

(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)))

Now in Java I simply would have said

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

What I am asking is this: Is there a better way to write this Lisp conditional? If I had to check for a larger range of ages then the code would get incredibly tedious using this method. Is there a way in Lisp to check for 2 conditions within one if statement like I did above in Java? Thank you so much for looking over this code and for any future responses!

Questioner
Xuluu
Viewed
0
46.7k 2016-01-20 07:03:34

Lisp has an AND operator that can be used to combine multiple conditions.

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

You can also do it with a single function call (<= 2 x 5) or (>= 5 x 2) to test if x is between 2 and 5 inclusive.

But if you test (< x 2) first, you don't need to test whether (>= x 2) after that, since conditions are tested in the order given.

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