NEWBIE-ish: data as code

Q&A's, tips, howto's
Locked
bugmagnet
Posts: 2
Joined: Sun Mar 17, 2013 8:37 am

NEWBIE-ish: data as code

Post by bugmagnet »

It's been a few years since I last did anything with NewLISP. I ought to know the answer to this ...

Can I use data as code? Can I have the name of a function in a string variable and execute the contents of that variable as if it were the name of a function? For example:

Code: Select all

(set 'f "even?")
(f 2.5)
As it stands, that'll give "e" because NewLISP will be thinking I want the 3rd character in the 'f variable. How do I get "even?" to execute against 2.5 (or am I hoping for too much)?

Kind regards,
Bugmagnet

bugmagnet
Posts: 2
Joined: Sun Mar 17, 2013 8:37 am

Re: NEWBIE-ish: data as code

Post by bugmagnet »

Hmm ... (reading the friendly manual) ... eval-string would seem to be best approach, yes?

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Re: NEWBIE-ish: data as code

Post by cormullion »

Yes, code is data is code, true, but code consists of strings, symbols, and numbers. So you'll need to move between the different elements of code, using functions such as as eval-string and sym:

Code: Select all

(set 'f "even?")
(apply (sym f) '(2))
;-> true
(map (sym f) '(2 3 4 5))
;-> (true nil true nil)
(map (eval-string "even?") '(2 3 4 5))
;-> (true nil true nil)
(eval-string "(even? 3)")
;-> nil
(eval (read-expr "(even? 4)"))
;-> true

Locked