Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Generation in Clojure

Tags:

clojure

(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:

  1. 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.

  2. 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".

like image 463
Joshua Hayworth Avatar asked Oct 26 '09 22:10

Joshua Hayworth


1 Answers

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
like image 169
Brian Carper Avatar answered Sep 16 '22 13:09

Brian Carper