fun with eval
Posted: Thu Aug 28, 2008 3:02 am
Eval is such a powerful function I know I will not think of all the cool things it can do.
the basic function is like this
(eval expression)
it has four basic modes (two that are trivial)
(eval number) returns that number
(eval function) returns that function
the two interesting cases are
(eval list) and (eval string)
if the expression is a list it will run that list as a called function
for example (eval (list "cat" 1 1)) will give you 11
so as you can see you can build your own code with this and run it
if the expression is a string it will treat that string as the name of the variable. (sorry it is hard to explain just think of this case as the opposite of set)
for example
(setq bob 11)
(setq myVar "bob")
(eval myVar)
the eval will return 11
beyond confusing people who look at your code what use is this?
well other than the storing code for later use you can store something that could be a global variable or a function. So say you have some data in a system some need a function called to find the data but some can just look at a global variable. With one simple line of code you can do both.
With this and apply you can have a class of things (like an item) where some have one function and others have different functions.
As I said earlier this is so powerful I know I am only scratching the surface if anyone else wants to add something please speak up or if you don't understand something please tell me so I can improve on this.
the basic function is like this
(eval expression)
it has four basic modes (two that are trivial)
(eval number) returns that number
(eval function) returns that function
the two interesting cases are
(eval list) and (eval string)
if the expression is a list it will run that list as a called function
for example (eval (list "cat" 1 1)) will give you 11
so as you can see you can build your own code with this and run it
if the expression is a string it will treat that string as the name of the variable. (sorry it is hard to explain just think of this case as the opposite of set)
for example
(setq bob 11)
(setq myVar "bob")
(eval myVar)
the eval will return 11
beyond confusing people who look at your code what use is this?
well other than the storing code for later use you can store something that could be a global variable or a function. So say you have some data in a system some need a function called to find the data but some can just look at a global variable. With one simple line of code you can do both.
With this and apply you can have a class of things (like an item) where some have one function and others have different functions.
As I said earlier this is so powerful I know I am only scratching the surface if anyone else wants to add something please speak up or if you don't understand something please tell me so I can improve on this.