This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

absolute value conditional

3 posts · 3266 views

Hi,
I wrote the following 2 functions to return the absolute value of a number. They seem to work but If you could have a look and point out any mistakes in style, design, efficiency, etc.
(defun absvalue (n)                                                                                       
  "Returns the absolute value of the argument"                                                            
  (if (numberp n)                                                                                         
      (if (< n 0) (- n) n)                                                                                
      'it-is-not-a-number))                                                                               
                                                                                                          
(defun absval2 (n)                                                                                        
  "An alternative version of absvalue"                                                                    
  (cond ((and (numberp n) (< n 0)) (- n))                                                                 
        ((numberp n) n)                                                                             
        ('we-need-numbers)))    
Thank you.

Re: absolute value conditional

When checking arguments, it is often good to signal an error early. ("throw an exception" in C++/Java)
(unless (numberp n) (signal some-error))
(assert (numberp n) ...)
(check-type n number)
APIs that silently insert a failure token can be very hard to debug. Something will fail later, and you're left wondering "when did x become not-a-number?!??"

Re: absolute value conditional

Thanks a lot for your feedback.