From: ···@orsi.com
Subject: parsing numbers & error recovery
Date: 
Message-ID: <864398252.7293@dejanews.com>
I am trying to write code that accepts a string and returns a number if
the string represents a valid lisp number.  Although I could write new
code to do this, it strikes me as unnecessary since the facility
exists within Common Lisp itself to do this.

I would simply like to call the function read-from-string and if an
error occurs (such as EOF) recover by returning the original string.

Consider the following code segment: the use of ignore-errors bothers me a
little.  Is there a safer way to do this?

(defun parsenum (str)
   "If str is the printed representation of x, return a number
that satisfies (= (parsenum str) x) ==> T"
   (let ((f (ignore-errors (read-from-string str))))
      (if (numberp f)
         f
         str)))

-------------------==== Posted via Deja News ====-----------------------
      http://www.dejanews.com/     Search, Read, Post to Usenet
From: Barry Margolin
Subject: Re: parsing numbers & error recovery
Date: 
Message-ID: <5m4bn1$9lp@tools.bbnplanet.com>
In article <··············@dejanews.com>,  <···@orsi.com> wrote:
>I would simply like to call the function read-from-string and if an
>error occurs (such as EOF) recover by returning the original string.
>
>Consider the following code segment: the use of ignore-errors bothers me a
>little.  Is there a safer way to do this?
>
>(defun parsenum (str)
>   "If str is the printed representation of x, return a number
>that satisfies (= (parsenum str) x) ==> T"
>   (let ((f (ignore-errors (read-from-string str))))
>      (if (numberp f)
>         f
>         str)))

This is very much the type of code that IGNORE-ERRORS was designed for.
However, if it bothers you, you could make use of the eof-error-p argument
to READ-FROM-STRING to prevent EOF from causing an error:

(read-from-string str nil nil)

However, this will only help if the string is empty (except for
whitespace), as eof-error-p only controls what happens if EOF is reached
before reading anything.  If EOF is reached in the middle of the
representation of an object, an error will still be signalled.  So you'll
still need the IGNORE-ERRORS wrapper.
-- 
Barry Margolin, ······@bbnplanet.com
BBN Corporation, Cambridge, MA
(BBN customers, call (800) 632-7638 option 1 for support)
Support the anti-spam movement; see <http://www.cauce.org/>