LISP Concatenate variable name with a string -


i wondering if can in lisp :

i need declare n variables . n1,n2,n3...etc

(dotimes (i n) (setq (+ 'n i)) 

is possible ?

rainer joswig pointed out in comment code you've got doesn't work you're trying do, , explained why. if you're trying declare variables programmatically, you're going need source code manipulation, means need macro. in case, it's pretty easy. can define macro with-indexed-vars takes symbol, number, , body, , expands let variables you'd expect, , evaluates body within scope:

(defmacro with-indexed-vars ((var n) &body body)   "evalutes body within lexical environment has x1...xn declared variables let.  instance      (with-indexed-vars (x 5)       (list x1 x2 x3 x4 x5))  expands       (let (x1 x2 x3 x4 x5)       (list x1 x2 x3 x4 x5))  symbols naming variables declared let interned same package var.  variables initialized nil let."   (let ((name (symbol-name var)))     `(let ,(loop 1 n               collecting (intern (concatenate 'string name (write-to-string i))                                  (symbol-package var)))        ,@body))) 

then, can use this:

(with-indexed-vars (n 4)   (setq n3 "three")   (setq n4 4)   (list n4 n1 n3 n2))  ;=> (4 nil "three" nil) 

as sean allred notes in comment, sort of advanced topic beginning lisp programming. if know need n value cells, might use vector , aref access values:

(let ((ns (make-array 4 :initial-element nil)))   (setf (aref ns 2) "three")   (setf (aref ns 3) 4)   ns)  ;=> #(nil nil "three" 4) 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -