absolute value conditional

Discussion of Common Lisp

absolute value conditional

Postby sycamorex » Sun Oct 16, 2011 8:12 am

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.
Code: Select all
(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.
sycamorex
 
Posts: 15
Joined: Sat Oct 08, 2011 4:05 am

Re: absolute value conditional

Postby nuntius » Sun Oct 16, 2011 9:54 pm

When checking arguments, it is often good to signal an error early. ("throw an exception" in C++/Java)
Code: Select all
(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?!??"
User avatar
nuntius
 
Posts: 497
Joined: Sat Aug 09, 2008 10:44 am
Location: Burlington, MA

Re: absolute value conditional

Postby sycamorex » Tue Oct 18, 2011 3:13 pm

Thanks a lot for your feedback.
sycamorex
 
Posts: 15
Joined: Sat Oct 08, 2011 4:05 am


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 4 guests

cron