(Disclaimer: I am a C# guy. I've just started learning Clojure.)
I understand that a Clojure program has the ability to manipulate itself or easily generate other programs. It has something to do with everything in Clojure being a data structure and that generating programs would be the same as creating any other type of data structure.
Does anybody have a good sample program (or a reference to one) that shows this?
If you generate a program, can you "serialize" that program out to disk for later execution?
Just for reference:
I'm trying to play with Genetic Programming. I want to generate a lot of little programs, evaluate them, and use the successful ones to generate more programs. See more here and here.
I think I'm misusing terms here. By program I actually mean a clojure list and by Code Generation I mean "List Generation". I just need the list to contain actual function calls and parameters. I would need to be able to control when this list gets "executed".
Consider (+ 1 2)
. As data, it's a linked list of three items: the Symbol +
and two Integers. As code, it's a function call, saying "Call the function called +
with these two Integers as arguments and give me the result". You can do anything to this list that you can do to any other list of data. You can also eval
it to get a result.
user> (def x '(+ 1 2))
#'user/x
user> (first x)
+
user> (rest x)
(1 2)
user> (map class x)
(clojure.lang.Symbol java.lang.Integer java.lang.Integer)
user> (reverse x)
(2 1 +)
user> (concat x (rest x))
(+ 1 2 1 2)
user> (eval x)
3
user> (defn foo []
(let [ops '[+ - * /] ; SO's lisp-highlighting sucks
nums (repeatedly #(rand-int 5))
expr (list* (rand-elt ops) (take 10 nums))]
(prn expr)
(prn (eval expr))))
user> (foo)
(+ 4 1 0 3 2 3 4 3 1 2)
23
nil
user> (foo)
(- 1 3 2 2 1 2 1 4 0 1)
-15
nil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With