Negative infinity in Lisp
Asked Answered
P

2

6

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)))))
Peculate answered 12/12, 2011 at 13:31 Comment(0)
E
7

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))
Emotionalism answered 12/12, 2011 at 13:58 Comment(2)
Thanks. I was not aware max took an arbitrary number of arguments, but that provides an elegant solution.Peculate
Since functions in Common Lisp don't allow arbitrary long argument lists, it is best to replace APPLY with REDUCE. See the value of the variable CALL-ARGUMENTS-LIMIT . An implementation supports up to CALL-ARGUMENTS-LIMIT long argument lists. In your example it would mean that an implementation may fail to compute the maximum on CALL-ARGUMENTS-LIMIT + 1 long lists. Note that this the value of CALL-ARGUMENTS-LIMIT can be as small as 50 (!).Odoric
O
3

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
Odoric answered 12/12, 2011 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.