Re: Newbie: Convert String to Symbol?

From: Jeff (massung_at_gmail.com)
Date: 01/01/05

  • Next message: David Sletten: "Re: Another newbie question: if-elseif-elseif-elseif..etc."
    Date: Fri, 31 Dec 2004 23:47:17 GMT
    
    

    Jens Teich wrote:

    > My very first application in Lisp (LispWorks) is a calculator which
    > works quite well.
    >
    > I'm not satisfied with this code
    >
    > (cond
    > ((string= op "+") (+ y x))
    > ((string= op "*") (* y x))
    > ((string= op "/") (/ y x))
    > ((string= op "-") (- y x))
    > ((string= op nil) x)))
    >
    > Could be one line
    >
    > (funcall #'(??? op) x y)
    >
    > isn't it? But I'm missing the conversion from string to symbol!

    One "trick" I like to do, is to create a has table of strings or
    symbols that can be used for evaluation purposes later (especially when
    the symbols are specific and well defined). For example:

    (defparameter *ops* (make-hash-table :test #'equalp))

    (defmacro defop (symbol function)
      `(setf (get-hash ,(symbol-name symbol) *ops*) ,function))

    (defop + #'+)
    (defop - #'-)
    ; ...

    (defun eval-op (op x y)
      (let ((function (get-hash op *ops*)))
        (when function
          (funcall function x y))))

    This can be done numerous other ways as well (eg, using a list an
    ASSOC). Keep in mind, I wouldn't do this for your particular problem,
    simply because your symbols/functions map 1-to-1 and have the same
    name. However, this "trick" is very nice when mapping assembler
    mnemonics, etc. HTH,

    Jeff M.

    -- 
    http://www.retrobyte.org
    mailto:massung@gmail.com
    

  • Next message: David Sletten: "Re: Another newbie question: if-elseif-elseif-elseif..etc."

    Relevant Pages

    • A neat trick to serialize arrays and hashes
      ... who thinks that my trick is "obvious to everyone but inexperienced ... hashes -- that is, it can pack and unpack arrays and hashes to and ... I might want to serialize @a into a string for the purpose of storing ... array into a string like so: ...
      (comp.lang.perl.misc)
    • Re: Efficient use of results of [binary scan]
      ... And memory allocation is *definitely* comparatively slow ... The same trick is ... naif solution, for my 100K string. ... DOULOS - Developing Design Know-how ...
      (comp.lang.tcl)
    • Re: Fetch function names & prototypes?
      ... > although in C++ the prototypes are found in the header files included ... > string into the object file symbol table, ... trick would not allow a perfect/accurate type checking. ... arguments have complex data types, ...
      (comp.compilers)
    • Re: Concatenation
      ... You can use a nifty little trick here which utilises the difference between ... "some string" + Null results in Null ...
      (microsoft.public.access.queries)