Page 1 of 1

calling context functions indirectly

Posted: Wed Nov 08, 2006 5:38 pm
by cormullion
What I'm trying to do here is pass functions and contexts around, but I can't get the functions to execute.

Code: Select all

(context 'TEST0)
  (define (TEST0:foo)  
    (println "hi there from TEST0:foo"))
  (define (TEST0:bar)  
    (println "hi there from TEST0:bar"))

(context 'TEST1)
  (define (TEST1:foo)  
    (println "hi there from TEST1:foo"))
  (define (TEST1:bar)  
    (println "hi there from TEST1:bar"))

(context 'TEST2)
  (define (TEST2:foo)  
    (println "hi there from TEST2:foo"))
  (define (TEST2:bar)  
    (println "hi there from TEST2:bar"))
  
(context MAIN)
  (set 'contexts '(TEST0 TEST1 TEST2))
  (set 'functions '({foo} {bar}))
  (dolist (c contexts)
    (map (fn (f) (eval (sym f c))) functions)             ; <- doesn't do what I thought it might :-)
    )
The required output is for all available contexts to run their functions when called upon to do so. eval should be able to execute the function...?

Posted: Wed Nov 08, 2006 6:09 pm
by rickyboy
Aren't you missing an extra pair of parentheses, i.e. around the eval call?

--Rick

Posted: Wed Nov 08, 2006 6:54 pm
by cormullion
rickyboy wrote:Aren't you missing an extra pair of parentheses, i.e. around the eval call?

--Rick
yes, I am! Thanks for spotting that - it wouldn't have looked right to me so i would never have tried it!

cheers

Posted: Wed Nov 08, 2006 7:50 pm
by Lutz
Rick's recommendation is correct, but there is an (perhaps easier to understand?) alternative using 'apply':

Code: Select all

(context MAIN)
  (set 'contexts '(TEST0 TEST1 TEST2))
  (set 'functions '({foo} {bar}))
  (dolist (c contexts)
    (map (fn (f) (apply (sym f c))) functions)   
    )
The effect is the same. Rick's extra parenthesis puts the lambda expression contained in the symbol (sym f c) and extracted by 'eval' into an applicative contextus. 'apply' does the same.

Lutz

Posted: Wed Nov 08, 2006 10:00 pm
by cormullion
Thanks. "applicative contextus", eh? My Latin is not as fluent as my newlisp these days...

It's been an educational week, what with all that integer business as well...