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

Re: string > symbol?



Laura Allender writes:
> >    (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
> >
> 
> When the heck would I want |(cons 1 2)| as a symbol?  Intern can be handy,
> but in many systems you don't just want a symbol back, you want a symbol if
> it's a symbol, a list if it's a list and a keyword if it's a keyword.
> I can always write a cond statement (or multiple methods) to handle these
> different cases.  That's the nice thing about a litely typed language, you
> don't
> have to have lots of different code for different kinds of data -- the code
> can handle it as long as your code is prepared for the alternatives.

The original poster wanted to create a symbol from a string.  What I
was trying to illustrate was the danger of using read-from-string for
that purpose.  Specifically, intern will *always* return a symbol
whereas read-from-string can return any datatype at all.  Intern does
exactly the intended operation and no more; read-from-string does lots
of things in addition to the intended operation.

Yes, you can check if the result is a symbol, and yes, there are not
many times that you would want the symbol |(cons 1 2)|; but if you
want to make a symbol from a string, then use intern.  Your program
will run faster, be clearer to read, and be more robust.

Kevin Gallagher