Hacker News new | ask | show | jobs
by majormunky 1250 days ago
I'm also learning lisp, mainly as a part of learning emacs, so I may not be super accurate here. In python, when you have a reference to a function, its a bit opaque, you can tell the thing is a function, but I don't think you can really go into the function object, and alter it lets say. You may be able to using the AST or something, but its not a "first-class" thing you can do.

In lisp (and code is data, data is code), the function is also a list, so you would be able to use all the normal programming tools to iterate over the list, add new items to the list, etc, which can change how the function runs.

2 comments

This is not what "code is data" is supposed to mean. It means "source code is data": the source code of Lisp is a data structure.

You shouldn't do it in any Lisp production code. E.g. in ANSI Lisp, self-modifying code is undefined behavior. Even if you get some expected results, it may not work portably, and won't work if the code is compiled. Compiled Lisp code doesn't have a list representation any more.

Code-is-data lets us have a transformation pass on the code with application-defined rules, before it is interpreted or compiled. This is a recursive step that returns a new version of the code based on the old

Such a concept could use an example to solidify that point.

If I have a function Foo that adds two numbers together. How is that represented in lisp (as a list you say?)? How would one alter that function/lisp-list: to multiply numbers instead?

> How is that represented in lisp (as a list you say?)

I'm only a beginner in lisp too, but it as simple as

    (defun add-numbers (a b) (+ a b))
if you look at it as "everything between () is a list" then you'll find the above code is actually:

    [word word [word word] [word word word]]
to get it to multiply numbers instead, you'd just get the last item of the list `(+ a b)` -- replace the first item `+` with `*` (using other list functions, etc..) and then re-evaluate the entire list again,

So now your function will multiply values instead of adding them..

The "power" aspect comes from the fact that we use "other list functions" to change the code, ie: code is data that we can manipulate.

note, probable errors, like I said, I'm new

I've not really encountered any situations where I've needed to do anything like this yet (still learning), but, I found this example, where there's an existing function, and someone alters the body of the function to create a new function. My guess is that there's various ways of doing this type of stuff: https://stackoverflow.com/a/1220198

Edit: a macro example, which I think may be the more common route of doing this type of stuff? https://lisp-journey.gitlab.io/blog/common-lisp-macros-by-ex...