Clojure self-modifying code

One of the advantages of having my computer, and all software, re-built is the opportunity to start over.

I just re-installed Clojure.  I seem to have a backup of one project I was working on, but haven’t looked at how recent, so I’m not sure how much I saved or lost.  That aside, I thought I’d do an experiment in self-modifying code.

This is not exactly what is meant, but in a sense it is:

(def f '(fn [x] (+ x 5)))
(def add-some (eval f))
(println "add-some a func?" (fn? add-some))
(println "result =" (add-some 13))
(def l (first (rest (rest f)))) ; one short-cut
(def l2 (cons (first l)
	      (list (first (rest l))
(println "re-defining, kinda cumbersome, but this is only an example")
(def f2 (list 'fn '[x] l2))
(println "original list was:" f)
(println "new list is:" f2)
(def add-more (eval f2))
(println "new function result =" (add-more 13))

So what is this code? what does it do?  I define a list named f (note the single-quote at the beginning — this says don’t evaluate the list, but store it).

Then I define a function (similar to defn, but expanded) using eval of that list; testing that it is a function, and using it (the result is 18).

Next, I “modify” the list [actually, I create a 2nd list], and “re-define” the function.  Well, it’s not exactly what I was after, but I am going to “publish” my result for now, maybe add more later…

Knowing how way leads on to way
I doubted if I should ever come back

Ah, well.  If you, my dear reader, should ask questions, I’d be more than happy to answer them.

A short paragraph explaining why I blog: there are two reasons.  The first is for my own personal record of what I did, or didn’t do.  The second is if someone finds entertainment, education, or some sort of connection with what I do, then please leave a comment so I know you’re out there.
I think I would write more, and more often, if I knew I had an audience.  Or maybe not, but at least I’d have a better focus than what I just wrote.


2 Responses to “Clojure self-modifying code”

  1. Ted Tower Says:

    I must admit, I just appreciate the combination of coding and your use of the english language. You’re a bit of a Renaissance man to me. Keep writing. I’m out here!

  2. gparks Says:

    thanks — sorry I respond sooner; I was on va-cay, but am home now.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: