Author Topic: cons + eval  (Read 1272 times)

0 Members and 1 Guest are viewing this topic.

kruuger

  • Swamp Rat
  • Posts: 633
cons + eval
« on: March 09, 2017, 09:01:15 AM »
hi
not sure how to properly type the subject but here is the issue
pseudo code which i want to execute.

we have subroutine _sum
than list of dotted pairs lst
now i want to go thru this list (assoc) and look for SearchFor.
if founded than eval correct _sum

Code: [Select]
(defun _sum (a b) (+ a b))


(setq lst
  (list
    (cons "One"   '(_sum 1 1))
    (cons "Two"   '(_sum 2 2))
    (cons "Three" '(_sum 3 3))
  )
)

(setq SearchFor "Two")

(if (setq res (assoc SearchFor lst))
  (ok so (eval (cdr res)) to run (_sum 2 2))
  (wrong)
)
hope it is clear
thanks
kruuger

VovKa

  • Water Moccasin
  • Posts: 1629
  • Ukraine
Re: cons + eval
« Reply #1 on: March 09, 2017, 09:13:44 AM »
what is the question?

Grrr1337

  • Swamp Rat
  • Posts: 812
Re: cons + eval
« Reply #2 on: March 09, 2017, 09:18:18 AM »
I think this is what you're asking:
Code - Auto/Visual Lisp: [Select]
  1. (defun _sum (a b) (+ a b))
  2.  
  3. (setq lst
  4.   (list
  5.     (cons "One"   '(_sum 1 1))
  6.     (cons "Two"   '(_sum 2 2))
  7.     (cons "Three" '(_sum 3 3))
  8.   )
  9. )
  10.  
  11. (setq SearchFor "Two")
  12.  
  13.   (eval (cdr (assoc SearchFor lst)))
  14.   (princ "\nWrong.")
  15. ); or

or access the item as a symbol (lazy way):
Code - Auto/Visual Lisp: [Select]
  1. (or
  2.   (eval
  3.     (cdr
  4.       (assoc 'Two '( (One _sum 1 1) (Two _sum 2 2) (Three _sum 3 3) ) )
  5.     )
  6.   )
  7.   (princ "\nWrong")
  8. );or
(apply ''((a b c)(a b c))
  '(
    (( f L ) (apply 'strcat (f L)))
    (( L ) (if L (cons (chr (car L)) (f (cdr L)))))
    (72 101 108 108 111 32 87 111 114 108 100)
  )
)
vevo.bg

Lee Mac

  • Seagull
  • Posts: 12913
  • London, England
Re: cons + eval
« Reply #3 on: March 09, 2017, 12:37:46 PM »
Since the list does not contain variable data, the entire list may be quoted as a literal e.g.:
Code - Auto/Visual Lisp: [Select]
  1. (defun _sum ( a b ) (+ a b))
  2.  
  3. (setq lst
  4.    '(
  5.         ("One"   _sum 1 1)
  6.         ("Two"   _sum 2 2)
  7.         ("Three" _sum 3 3)
  8.     )
  9. )
  10. (if (setq expr (cdr (assoc "Two" lst)))
  11.     (eval expr)
  12.     (princ "\nNot found.")
  13. )

Alternatively:
Code - Auto/Visual Lisp: [Select]
  1. (defun _sum ( a b ) (+ a b))
  2.  
  3. (setq lst
  4.    '(
  5.         ("One"   1 1)
  6.         ("Two"   2 2)
  7.         ("Three" 3 3)
  8.     )
  9. )
  10. (if (setq args (cdr (assoc "Two" lst)))
  11.     (apply '_sum args)
  12.     (princ "\nNot found.")
  13. )

kruuger

  • Swamp Rat
  • Posts: 633
Re: cons + eval
« Reply #4 on: March 09, 2017, 02:52:16 PM »
omg  :uglystupid2:  not sure why i expect cons this format to work with assoc:
("Two" . _sum 2 2)
and stop testing routine my routine. it looks like all was almost done.
thanks guys, all works fine.