Skip to content
HN On Hacker News ↗

The Magic of Partial Evaluation — Jimmy Miller

▲ 117 points • 40 comments • by aray07 • 5d ago • HN discussion ↗

Pangram verdict · v3.3

We believe this text is mainly human-written, with some AI content.

7 %

AI likelihood · overall

Human
93% human-written 7% AI-generated
SEGMENTS · HUMAN 1 of 2
SEGMENTS · AI 1 of 2
WORD COUNT 1,595
PEAK AI % 100% · §2
Analyzed
Nov 18
backend: pangram/v3.3
Segments scanned
2 windows
avg 798 words each
Distribution
93 / 7%
human / AI fraction
Verdict
Human
Pangram v3.3

Article text · 1,595 words · 2 segments analyzed

Human AI-generated
§1 Human · 0%

There are certain ideas in software that are simply beautiful. It doesn't matter if they have any practical use. It doesn't matter that you will never convince your coworkers to consider them. There is just something captivating about the way some computational systems work. For me, the most beautiful pieces of software are those that reveal something about the nature of programming languages. Programming languages are my obsession. I have never met a problem that couldn't be solved by introducing yet another programming language. Solving a problem at the programming language level is about solving the meta problem. Instead of trying to solve a particular problem, we take a step back and ask how we can solve a whole class of problems at once. So when I find something that makes me rethink the nature of programming languages, I start rethinking computation as a whole. One of these incredibly beautiful but tricky concepts goes by the name partial evaluation. If you are fascinated by interpreters and compilers, partial evaluation will teach you how they are related, and how you can get a compiler for free. Partial Evaluation Easy Mode# Partial evaluation has been a fascination of mine for a while. But this whole thing came up when James Long announced he had revived Meta's partial evaluator for JavaScript called prepack. When I first heard about prepack, I had some high hopes and expectations for the project, but was sadly let down. This revival brought to light those same dreams. But sadly, just as with the original aim, prepack was not designed for beauty, but for practicality. So I figured it was time to renew my own efforts. Yes, in some ways this is a post repping my own library I'm releasing. But I'm not doing this because I want it to be used. I'm doing this because it lets you play with the idea I find so beautiful. That is what this post is about. Doing Partial Evaluation by Hand# Consider the following code: function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); } factorial(5); As a person who reads code, you can think about how this code computes and what answer it will give. But you can do more than just give the answer. You can see the expanded form of this particular code for these particular calls. This code is spiritually the same as the following expression, once we expand it out. 5 * (4 * (3 * (2 * 1))) In this case, there is really nothing at all that this code needs to do at runtime. A sufficiently smart compiler will just run this code directly at compile time and give the answer. But this is a bit less clear if things come in at runtime. function power(base, exponent) { if (exponent === 0) return 1; return base * power(base, exponent - 1); } power(process.argv[2], 5) It might seem like we can't do anything here, but again, if you are used to thinking about how programs run, you can trace this out and realize this is just the same as: process.argv[2] * (process.argv[2] * (process.argv[2] * (process.argv[2] * (process.argv[2] * 1)))) What we have done in both of these cases is called partial evaluation. In the first, it was a trivial case because everything was statically known. But in this latter case, we have reduced a program down into the essentials of its dynamic structure. There are no recursive function calls left. All of this has been expanded as far as it could till we get just the dynamic parts of the code remaining. The Big Idea# This intuitive notion of partial evaluation is all you need to know to appreciate the beauty here. Partial evaluation just evaluates the part of the program we can evaluate at build time and leaves all the rest. When we do this with certain programs in certain combinations, we get some quite surprising, incredible behavior. function calculate(expr) { if (typeof expr === "number") return expr; switch (expr[0]) { case "+": return calculate(expr[1]) + calculate(expr[2]); case "-": return calculate(expr[1]) - calculate(expr[2]); case "*": return calculate(expr[1]) * calculate(expr[2]); case "/": return calculate(expr[1]) / calculate(expr[2]); default: throw new Error("Unknown operator"); } } calculate(["+", 1, ["*", 2, 3]]); Here we have a very simple interpreter for a language that just supports arithmetic. For the above expression, you should be able to think about how we could start "partially" evaluating it. (In this case, it can be a full evaluation.) If this kind of partial evaluation isn't quite clicking for you, I've put the steps below to hopefully help it make sense. calculate(["+", 1, ["*", 2, 3]]) → calculate(1) + calculate(["*", 2, 3]) → 1 + calculate(["*", 2, 3]) → 1 + (calculate(2) * calculate(3)) → 1 + (2 * calculate(3)) → 1 + (2 * 3) → 1 + 6 → 7 This is a simple evaluation of the code. But what happens if we throw a value we don't know into the expression? calculate(["+", Number(process.argv[2]), ["*", 2, 3]]) → calculate(Number(process.argv[2])) + calculate(["*", 2, 3]) → Number(process.argv[2]) + calculate(["*", 2, 3]) → Number(process.argv[2]) + (calculate(2) * calculate(3)) → Number(process.argv[2]) + (2 * calculate(3)) → Number(process.argv[2]) + (2 * 3) → Number(process.argv[2]) + 6 Here we can see that clear partial evaluation difference. We don't know how to evaluate Number(process.argv[2]). We have no idea what the answer to that will be. But as part of this process, we do know some partial information about it. For example, when we get to if (typeof expr === "number") return expr; we know that Number(process.argv[2]) is indeed a number. So we can partially evaluate it further. Hopefully this is all making sense. But if you are like me, this all might seem a bit trivial and uninteresting. So let's look at a more complicated example. function brainfuck(code, input = "") { const tape = new Uint8Array(30000); const jumps = {}, stack = []; let pointer = 0, inputPointer = 0, output = ""; for (let i = 0; i < code.length; i++) { if (code[i] === "[") stack.push(i); if (code[i] === "]") { const start = stack.pop(); jumps[start] = i; jumps[i] = start; } } for (let i = 0; i < code.length; i++) { switch (code[i]) { case ">": pointer++; break; case "<": pointer--; break; case "+": tape[pointer]++; break; case "-": tape[pointer]--; break; case ".": output += String.fromCharCode(tape[pointer]); break; case ",": tape[pointer] = inputPointer < input.length ? input.charCodeAt(inputPointer++) : 0; break; case "[": if (!tape[pointer]) i = jumps[i]; break; case "]": if (tape[pointer]) i = jumps[i]; break; } } return output; } brainfuck("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."); Here we have a brainfuck interpreter. And the example program we want to partially evaluate does not require any input at all (in brainfuck , is the way you get input). So when we go to partially evaluate this, we will just get an answer. In this case, this program is actually brainfuck's "hello world". But what about a program with input? function main() { return brainfuck(",>++[>+++[>++++[<<<+>>>-]<-]<-]<.", process.argv[2]) } When we do our partial evaluation, we get the following: function main(b) { let a; a: { a = process.argv[2]; a = a === void 0 ? "" : a; if (0 < a.length) { a = a.charCodeAt(0); break a; } a = 0; } a = (a & 255) + 24 & 255; return String.fromCharCode(a); } What is this? A compiled brainfuck program! This is the first incredible fact: when you take an interpreter and partially evaluate it with a program, you get the compiled program out! Now this particular exact form is an artifact of how my partial evaluator works. You could imagine slightly different code. But the key is that what we've done is remove the interpreter completely. The Projections# What we've discovered here is the first of three so-called Futamura Projections. Our partial evaluator, when applied to an interpreter and given a program, can give us a compiled version of that program. Or to put it in pseudocode. partial_eval(interpreter, prog) -> compiled_prog Depending on your exposure to interpreters and compilers, this might seem miraculous or mundane. Writing an interpreter and writing a compiler can seem like significantly different undertakings. In the age of AI, perhaps less so, but I think even then many things still hold. It is quite easy to instrument an interpreter, quite a bit harder to do so for a compiler. Changing an interpreter to support new features is quite easy, less so for a compiler. But more than that, there are all sorts of things that can be thought of as interpreters, that we'd almost never write a compiler for.

§2 AI · 100%

function validate(schema, value) { switch (schema.type) { case "string": return typeof value === "string" && (schema.minLength === undefined || value.length >= schema.minLength); case "number": return typeof value === "number" && Number.isFinite(value) && (schema.min === undefined || value >= schema.min); case "boolean": return typeof value === "boolean"; case "array": if (!Array.isArray(value)) return false; const length = value.length; for (let i = 0; i < length; i++) { if (i in value && !validate(schema.items, value[i])) return false; } return true; case "object": return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(schema.properties).every(key => Object.hasOwn(value, key) && validate(schema.properties[key], value[key])); default: throw new Error("Unknown schema type: " + schema.type); } } const userSchema = { type: "object", properties: { name: { type: "string", minLength: 1 }, age: { type: "number", min: 0 }, tags: { type: "array", items: { type: "string" } } } }; function validateUser(value) { return validate(userSchema, value); } Consider this simple schema setup.