Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative infinity in Lisp

Tags:

lisp

fixnum

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)))))
like image 421
jforberg Avatar asked Dec 12 '11 13:12

jforberg


2 Answers

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))
like image 162
Daimrod Avatar answered Sep 28 '22 08:09

Daimrod


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
like image 30
Rainer Joswig Avatar answered Sep 28 '22 09:09

Rainer Joswig