Hacker News new | ask | show | jobs
by aufreak3 4577 days ago
And then there is this whole other category of self-modifying programs - programs that know about their own structure and can change themselves at runtime. This is (almost) in the "unthinkable" category for non-homoiconic languages.
2 comments

This was, in fact, more or less pioneered in languages that aren't homoiconic in the same manner as Lisp is (code that used self-modification for reasons like time or space optimization was, if not common, at least known of in the early days of electronic computers). Arguably, machine code is very much homoiconic; what is beautiful about Lisp is that the underlying structure of program/data is regular and nicely-abstracted.
I think you could solve most of the problems that you'd need this property for with closures. If the bulk of the execution is defined with them, and you have closures defining which other closures to run, you can have them swap each other out.
I'm not sure I understand what you have in mind. Assuming I have something like this:

int foo(void) { return bar(1) + 2; }

is there any way in which I could arbitrarily modify this function? E.g. to dynamically turn it into

int foo(void) { return bar(2) * 4 }

using closures?

I get how you could do that, assuming you had a function defined for each of the possible operations you needed. But what about arbitrary modifications?

You wouldn't want to modify the function in-place, that would violate immutability of data. Each of these closures would themselves be generated, by a factory method. When you're ready to modify, you'd invoke the factory to generate another closure, then you'd use whatever infrastructure you built to assign them in the first place to re-assign them to the new closures.
Ah, got it. Thanks!
If you wanted to get really sophisticated, you could generate the factory methods, too.