I'm looking for the standard way to represent negative infinity in Lisp. Is there a symblic value which is recognised by Lisp's arithmetic functions as less than all other numbers?
Specifically, I'm looking for an elegant way to write the following:
(defun largest (lst)
"Evaluates to the largest number in lst"
(if (null lst)
***negative-inifinity***
(max (car lst) (largest (cdr lst)))))
ANSI Common Lisp has bignum
, which can used to represent arbitrarily large numbers as long as you have enough space, but it doesn't specify an "infinity" value. Some implementations may, but that's not part of the standard.
In your case, I think you've got to rethink your approach based on the purpose of your function: finding the largest number in a list. Trying to find the largest number in an empty list is invalid/nonsense, though, so you want to provide for that case. So you can define a precondition, and if it's not met, return nil
or raise an error. Which in fact is what the built-in function max
does.
(apply #'max '(1 2 3 4)) => 4
(apply #'max nil) => error
EDIT: As pointed by Rainer Joswig, Common Lisp doesn't allow arbitrarily long argument lists, thus it is best to use reduce
instead of apply
.
(reduce #'max '(1 2 3 4))
There is nothing like that in ANSI Common Lisp. Common Lisp implementations (and even math applications) differ in their representation of negative infinity.
For example in LispWorks for double floats:
CL-USER 23 > (* MOST-NEGATIVE-DOUBLE-FLOAT 10)
-1D++0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With