[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: string > symbol?



Douglas C. Merrill wrote:
>
> (Steve Hain) wrote:
> 
> > At 10:43 AM 3/17/95, Ken Tilton wrote:
> > >We keep running into the need to make a string into a symbol, but things are
> > >not going well.
> > >
> > >"intern" is not really working for us, but I gather that is the way to go.
> > >here's the scoop.
> 
> You might try messing with read-from-string (it returns multiple values,
> but you can ignore the extra args) -- you'll need to preface it with
> something like string-left-trim, etc.

No!

An excellent programming principle is to use the least powerful method
for acheiving your objective.  This is especially important in lisp
because there are always several ways to do something, each with
widely differing costs.  Additionaly, using a function that does
exactly what you want -- and no more -- makes your intent much clearer
to anyone reading your code.  Using a big stick when a small one will
do will make your program run slower, make it harder to understand,
probably lead to unexpected bugs, and contribute to the misperception
that `lisp is slow.'

In the case of converting a string to a symbol use INTERN.  INTERN looks
for an existing symbol with the specified name and creates one if no
such symbol exists.  It returns the symbol that was found or created.
(If you expect the symbol to already exist you should use FIND-SYMBOL
which returns nil if no symbol with the specified name is found.)

As was pointed out in other messages, INTERN doesn't do case conversion
or anything else.

    (intern "Foo") => |Foo|
    (intern "FOO") => FOO

The function READ-FROM-STRING is too big a stick.  It invokes the lisp
reader which is a large program by itself.  (On my Explorer (intern
string) is 6-7 times faster than (read-from-string string) and it
doesn't cons at all.)  Even worse, because READ-FROM-STRING can return
any datatype your program will break if you expect a symbol, but
READ-FROM-STRING reads a number instead.  (In fact, because of read
macros, READ-FROM-STRING can *do* anything.  It might not even return
at all.)  If you use INTERN you will be assured of getting back a
symbol.

    (intern "(cons 1 2)") => |(cons 1 2)|              ;; A symbol

    (read-from-string "(cons 1 2)" => (CONS 1 2)       ;; A list

    (catch 'exit (read-from-string "#.(throw 'exit 'dumb)")) => DUMB

EVAL, READ, and READ-xxx are the functions that are most overused when
a smaller stick will do.  They have their place, but that place should
be small and well defined.  Also, FORMAT and the other printing
functions can often be replaced with less powerful (and less costly)
functions.

Kevin Gallagher
________________________________________________________________________
Blackboard Technology Group, Inc.
401 Main Street                                      Phone: 413-256-8990
Amherst, MA 01002                                      Fax: 413-256-3179