Author Topic: 'max 'min test with (=) or (equal)  (Read 1037 times)

0 Members and 1 Guest are viewing this topic.

David Bethel

  • Swamp Rat
  • Posts: 656
'max 'min test with (=) or (equal)
« on: March 24, 2016, 01:02:02 PM »
Greetings again.

I'm having to make a simple roll your own number only sort

I'm trying to think of a scenario where
                (apply 'max lst)
  would require (equal)
  in lieu of a  (=)

I could end up with a infinite loop if = doesn't hold true
But could also end up with a error return with a > or < call later
  if the fuzz factor is too large


Code - Auto/Visual Lisp: [Select]
  1. (defun nw_nsort (l f / c s e m r)
  2.   (while l
  3.     (setq m (apply (if (eq f '<) 'min 'max) l)
  4.           r nil)
  5.     (foreach n l
  6.       (if (= m n)                  ;if the number = the max/min of the remaining list
  7.           (setq s (cons n s))      ;then add the number to the sorted list
  8.           (setq r (cons n r))))    ;else add the number to the remaining list
  9.     (setq l r))
  10. s)                                 ;return the sorted list
  11.  

Code - Auto/Visual Lisp: [Select]
  1.   (trace nw_nsort)
  2.   (setq b -10 e 50.5 x nil)
  3.   (repeat 50
  4.     (setq x (cons b x)
  5.           x (cons e x)
  6.           b (1+ b)
  7.           e (1- e)))
  8.  
  9.   (setq x (cons pi x))
  10.   (setq x (append x (list 3 3 3 3 3)))
  11.  
  12.   (nw_nsort x '>)
  13.  

The basis for this that I need access some of the values as
they are being sorted.  I wouldn't recommend this for a large list.

Thanks!  -David
R12 Dos - A2K

Lee Mac

  • Seagull
  • Posts: 12912
  • London, England
Re: 'max 'min test with (=) or (equal)
« Reply #1 on: March 24, 2016, 01:30:06 PM »
Since you are not performing arithmetic operations on the numerical data, you should theoretically be safe to use the '=' function for a comparison, but I would personally still stick to using equal with a small tolerance.

Here's another approach which may be more efficient and avoids such comparisons:
Code - Auto/Visual Lisp: [Select]
  1. (defun LM:sort ( l f )
  2.     (if l (LM:sort:recurse (car l) (cdr l) f))
  3. )
  4. (defun LM:sort:recurse ( x l f / m n )
  5.     (foreach y l (if (f x y) (setq m (cons y m)) (setq n (cons y n))))
  6.     (append (LM:sort n f) (list x) (LM:sort m f))
  7. )
Code - Auto/Visual Lisp: [Select]
  1. _$ (LM:sort '(6 5 4 3 3 2 1) <)
  2. (1 2 3 3 4 5 6)

David Bethel

  • Swamp Rat
  • Posts: 656
Re: 'max 'min test with (=) or (equal)
« Reply #2 on: March 24, 2016, 01:59:31 PM »
Thanks Lee,  I try it out.  -David
R12 Dos - A2K