News for hackers. Stuff that matters.
Re:What is a programmable programming language? (2019) by account-5 on Monday June 06, 2022 @02:23AM (#31637723)
I'm wanting to learn lisp, can someone eli5 metaprogramming?
Re:What is a programmable programming language? (2019) by reikonomusha on Monday June 06, 2022 @02:37AM (#31637796)
Sometimes you're writing code, and you want to be able to express an idea that your language does not elegantly support. But you know how to express the idea, but it takes a lot of boilerplate, or is just a massive nuisance to write.

Metaprogramming allows you to write a function that generates the boilerplate, and transparently use that function as if it's a brand new keyword in your programming language. That function in metaprogramming circles is called a "macro", not to be confused with C macros.

Stated another way: a macro = a function that takes as input the code you want to write, and provides as output code that your programming language can actually execute. (It's like a super miniature compiler.)

For example, let's pretend C is metaprogrammable.

Perhaps I want a new keyword "pfor" which is like "for" but executes the loop in parallel.

    int x[20];
    pfor(i = 0; i < 10; i++) {
        x[2*i] = expensive(2*i);
        x[2*i+1] = expensive(2*i+1);
    }
Here, we assume "expensive" is some really expensive function that maybe might take several seconds to execute, which is why we want to parallelize it.

This "pfor" is just a sort is pseudo code. In reality, you know how we would actually have to write this: make a loop in which we spawn 10 threads, set i to be a thread local variable in each, call a callback function in each thread

    void thread_callback(int i){
        x[2*i] = expensive(2*i);
        x[2*i+1] = expensive(2*i+1);
    }
and join the threads at the end. This would have the equivalent effect as our desired "pfor" keyword.

In a metaprogramming language, we can add this keyword by just telling the compiler what code to generate any time it sees "pfor". We could write something like

    macro pfor(var = init, cond, incr, body...) {
        symbol callback = generate_random_symbol();
        ```
        void $callback(int $var) {
            $...body;
        }
        vector threads;
        for($var = $init; $cond; $incr) {
            threads.push(make_thread($callback, $var));
        }
        for(t in threads)
            join_thread(t);
        ```
    }
The triple ``` starts a template, and the $ escapes a template. We have to generate a fresh symbol for the callback name so that they don't collide when we use "pfor" multiple times.

Now every time we use "pfor", the compiler will look at our homemade code generator function and write out the code for us.

So in effect by telling the compiler how "pfor" can be implemented in more basic code, we've added "pfor" to the language.

This isn't a separate tool however! It's not a pre-processor or anything like that. It's built in to the language (hence why it's a programming language paradigm).

Re:What is a programmable programming language? (2019) by shepherdjerred on Monday June 06, 2022 @03:01AM (#31637911)
Is there anything you can do with macros that you can’t do with similar language features like higher order functions?
Re:What is a programmable programming language? (2019) by reikonomusha on Monday June 06, 2022 @03:07AM (#31637941)
Yes. Macros are evaluated at compile-time. You can put arbitrary compile-time computation in a macro. For instance, you might want to initialize a look-up table at compile time. (Have you ever seen C code where it has a header file with a giant array of pre-computed constants, say, as a lookup table for values of sine? You can just generate that with a macro.)

Since macros in effect receive structured source code (basically an AST) as input, you can also do analysis of that code. For example, a macro to simplify algebraic expressions at compile-time.

Abstractions based on high-order functions also tend to allocate closures at run-time, so in practice you frequently get a performance penalty for their use.

High-order functions remove the need to use macros in some cases, but definitely don't replace all of them.

Re:What is a programmable programming language? (2019) by somewhereoutth on Monday June 06, 2022 @11:11AM (#31641513)
Not original questioner, but to rephrase the question slightly:

Is there anything you should do with macros that you can’t do with similar language features like higher order functions?

My concern with macros is that they are completely open-ended, so you can really do anything - and if you can do anything, then the language is not usefully defining a strict enough semantic structure. As an example, see the 'hygiene problem'.

Re:What is a programmable programming language? (2019) by ratzkewatzke on Monday June 06, 2022 @11:36AM (#31641819)
Without rat-holing on "should," here's something I had to do the other day:

I am providing language-level APIs for a complex web service, one in Python and one in Common Lisp. The service has dozens of operations, all of which are wrapped around a REST API that takes query strings and headers in its inputs, and produces very different outputs. Model for this is something like S3.

In most languages, I have two choices: I can push the complexity to the users, making them plug the query string values into a big map or option object; or I can write dozens of functions, most of which are boilerplate.

In Python I wrote dozens of functions (I obviously reused a set of central ones, but there's lots of scaffolding to do, e.g., translation of arguments from user types to strings appropriate HTTP headers). In Lisp I wrote a macro that operates on a set of query string and header inputs, and then defines a function appropriate for the user-level API. When I fix bugs in the macro, I automatically fix all of the functions.

The trade-off is that the macro is itself a function that's operating at two different semantic levels (pre- and post-compilation), and it might be challenging to read for newcomers to Lisps. But this let me hide all the nasty API complexity from my users while writing substantially fewer lines of code. New additions are a single defmacro line.

Re:What is a programmable programming language? (2019) by lispm on Monday June 06, 2022 @05:25AM (#31638541)
A Lisp macro sees the actual source it encloses and this source does not need to adhere to any pre-defined syntax.

For example: we may want a macro which outputs the source it encloses, before execution:

  CL-USER 12 > (defmacro my-loop (&body things)
                `(progn
                   (pprint (list :doing-loop-with ',things))
                   (loop ,@things)))
  MY-LOOP

  CL-USER 13 > (my-loop for i from 1 upto 3 sum
                (my-loop for j upto 3
                  sum (* i j)))

  (:DOING-LOOP-WITH
   (FOR I FROM 1 UPTO 3 SUM (MY-LOOP FOR J UPTO 3 SUM (* I J))))
  (:DOING-LOOP-WITH (FOR J UPTO 3 SUM (* I J)))
  (:DOING-LOOP-WITH (FOR J UPTO 3 SUM (* I J)))
  (:DOING-LOOP-WITH (FOR J UPTO 3 SUM (* I J)))
  36
A normal function can't do that, since it does not get source as an argument, but just sees the arguments values.

Since a macro sees source, it can not only print it, but also simplify, transform, mutate, etc. the source.

Re:What is a programmable programming language? (2019) by chriswarbo on Monday June 06, 2022 @05:40AM (#31638613)
You might want to look at Template Haskell, which is used for macros in Haskell (a language which already makes heavy use of higher-order functions).

One nice thing I've used macros for is reading and parsing files at compile-time, to bake-in data into programs. That way, the compiled programs just process stdio, without having to care about file paths, permission errors, parse errors, etc. (those all become compile errors)

Re:What is a programmable programming language? (2019) by mejutoco on Monday June 06, 2022 @03:06AM (#31637933)
Not OP, but the difference is you can run the code at compile time, so there is no performance penalty.
Re:What is a programmable programming language? (2019) by hutzlibu on Monday June 06, 2022 @06:03AM (#31638696)
Now I feel a bit pressure parenting wise, to push my kids, so they will be able to understand all of this, by the age of 5.

So I am not sure, I will succeed at it, but I am saving your comment, to try when they are ready. 10 years might be doable. Probably depends how many more times they hit their head..

(And whether I can spark enthusiasm in them, but robots are fun..)

Re:What is a programmable programming language? (2019) by speed_spread on Monday June 06, 2022 @09:37AM (#31640266)
> eli5 metaprogramming

Metaprogramming is "programming programming". Consider "programming" as writing a series of steps for a computer to follow. Metaprogramming is writing a series of steps for a computer to follow to write a series of steps for a computer to follow.

When working with LISP, metaprogramming is just a normal way to program things that's built into the language. Rather than writing everything as a linear program as you would in conventional languages, you can write a program that "writes itself" (or modifies parts of itself).

While you could meta-program in many languages (using code generators and whatnot), in LISP this is easy because the programs themselves are written in a way that makes them easy to be manipulated by other parts of the program. This is why you'll see so many parentheses when looking at LISP code. The simplicity of the syntax is also what makes it so powerful.

Metaprogramming is a technique that often results in much shorter programs which can make single programmers very effective. The downside is that the higher level of abstraction (leaving ELI5 zone here, sorry) can make the workings of LISP programs quite opaque to newcomers as things seem a lot like magic. Therefore preserving the metaprogramming advantages in larger teams requires _especially_ good documentation and attention to design.

Re:What is a programmable programming language? (2019) by Jtsummers on Monday June 06, 2022 @02:40AM (#31637815)
It can mean a few different things, in this case it's about programs that manipulate the program source and produce new programs (or program segments). Think of a code generator that can take a DSL and turn it into some valid (for execution) code:

  for i in 1 to 10 do printf("%d\n", i)
Becomes (through a preprocessor in this hypothetical system) valid C as:

  for(int i = 1; i <= 10; i++) { printf("%d\n", i); }
Now that's not too interesting, but it is a bit (subjective) nicer looping syntax than C's straight syntax. In the Lisp case, macros allow you to take an arbitrary set of values (the parameters to the macro) and produce some other value or values in their place. This could be just executing the code to get a kind of compile time evaluation:

  (hypotehtical-expression-evaluator-macro (complex-computation-that-gets-reused-100-times-but-takes-10-minutes-each-time))
Or it could be more transformative, like Lisp's loop macro that lets you write an Algol-ish loop instead of a lisp-y loop (or using recursion or other approaches):

  (loop for i from 1 to 10 do (print i))
Which gets transformed into some other valid Lisp code (not on my laptop so not in a position to actually show the result).

David Moon's "Moon's Mark Down" is actually a pretty neat case of Lisp meta programming. He defines a macro defdot which will take a name for a particular directive for his markdown syntax and generate all the necessary functions so that things "just work". And when parsing, when a . is found at the start of a line, the correct handler is calculated and called. To add a new directive, you add a new defdot and that macro will create the relevant functions and register the new handler.

http://users.rcn.com/david-moon/MMD/HTML/index.html

http://users.rcn.com/david-moon/MMD/MMD.lisp

Re:What is a programmable programming language? (2019) by timonoko on Monday June 06, 2022 @02:30AM (#31637762)
Old lisp makers rule was "macro is like lambda, but with one extra eval in the original environment".

In other words: if your function is able to produce (+ 1 2), same function produces 3, when used as macro.

Re:What is a programmable programming language? (2019) by rurban on Monday June 06, 2022 @02:37AM (#31637795)
macro is not like lambda. macros are like special forms.

a lambda evaluates all it's args, a macro not.

Re:What is a programmable programming language? (2019) by timonoko on Monday June 06, 2022 @05:07AM (#31638484)
My Bad. I have special nlambda, which does not evaluate anything at any stage. It was originally for testing macros without macroexpand, which expanded too much.
Re:What is a programmable programming language? (2019) by timonoko on Monday June 06, 2022 @05:14AM (#31638504)
I have also nslambda, which take only one argument. I think the macro in some ancient lisp was also like that. My macroes are called mlambda because of this confusion.
Re:What is a programmable programming language? (2019) by lispm on Monday June 06, 2022 @03:01AM (#31637907)
fexprs
Re:What is a programmable programming language? (2019) by Shorel on Monday June 06, 2022 @01:45PM (#31643429)
You write a program that writes part of the program for you.