cross-posted from: https://lemmy.ca/post/38996724

Hello,

the most powerful thing in elisp is program as data but what does it mean how can I run data as a program. I was confused too but here is what I found.

First I tried this:

(setq x '(+ 1 3))
(x)

basically setting the value of x as a list. now x is set to some code but when I try to run x as function using (x) syntax we get this error *** Eval error *** Symbol’s function definition is void: x. It tried to look for function in x but couldn’t find it. then how can I run the code that I stored in a variable? how to evaluate it? we need a built-in function eval.

If we run this code it works and outputs 4:

(setq x '(+ 1 3))
(eval x)

so yeah, it is how you can evaluate a code stored in a variable. feel free to correct me if there is another way to achieve it :)

  • Jerkface (any/all)
    link
    fedilink
    English
    arrow-up
    3
    ·
    8 days ago

    Your experiments bump into the difference between so called Lisp 1 and Lisp 2 systems. In Lisp 2 systems like elisp, variables and functions have separate namespaces. The same name can be bound to both a function and a variable, or to just one, or to neither. In your first example, you assign a value to the variable slot of x, but the function slot is still unspecified. So when you try to call it as a function, you are told that its “function definition is void” – it doesn’t have a function associated with it. In another lisp, that might have worked.

  • Jerkface (any/all)
    link
    fedilink
    English
    arrow-up
    2
    ·
    edit-2
    8 days ago

    That isn’t really what is meant by “code as data”. When your source code is read by lisp, before it executes it, it transforms it into data that can be examined or modified from other lisp code. One of the ways that we interact with this code-as-data is when we use metaprogramming techniques like macros. Another way that you are commonly exposed to is the (interactive) marker that begins certain functions. While it looks like a function call, IIRC the function call has no value or side effects, it does nothing at all. But it is visible in the code-as-data of the function, and emacs looks to see if a function starts with a call to interactive to determine whether or not a function is meant to be called interactively from M-x.

    • whoareuOP
      link
      fedilink
      arrow-up
      1
      ·
      8 days ago

      oh I didn’t know it, thank you so much for correcting me! =)

    • whoareuOP
      link
      fedilink
      arrow-up
      1
      ·
      8 days ago

      Thank you so much for providing these links, I will read it all.