I'm trying to get the maximum value from a list of numbers but the max() function doesn't work on list i.e. it needs each elements from the list to be defined as an argument. How can I get around this?
You can use the apply function, as in the following example:
mylist = list( 1 3 9 27 ) apply('max mylist) => 27
I hope that it helps you!
In reply to skillUser:
In reply to Yaosan:
If you are dealing with really long lists, (like over 60,000 items), you can run into a stack overflow using the apply on these lists. You can always use a sort:
mymax = car(sort(mylist 'greaterp))
In reply to dmay:
Sort on a copy of the list if you use that method and you need to retain the original list,
In reply to eDave:
Good point Dave. Sorts are "destructive" operations. Thanks for the clarification.
Note that using a sort to find the maximum is rather an expensive operation - you spend time and memory sorting all the elements, whereas all you want to do is find the largest.
With 1 million entries in the list, the sort takes 4.6 seconds for me (on my laptop), and with the copy too, it uses 12 million bytes (that's all from the copy). The following:
(defun abComputeMax (l)
(let ((mx (car l)))
(foreach val (cdr l) (when (greaterp val mx) (setq mx val)))
takes 0.16 seconds, and 140 bytes. Yes, I know, it's not exactly a massive amount of time - but even so, it adds up.