Re: Newbie: Convert String to Symbol?
From: Jeff (massung_at_gmail.com)
Date: 01/01/05
- Previous message: Jeff: "Re: What's so special about IF?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Previous message: Jeff: "Re: What's so special about IF?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|