Do you have a problem? Write a compiler! – Oleg Grenrus

Опубликовано: 03 Ноябрь 2024
на канале: Metosin
2,027
24

Imagine you are writing a cool game to be played in a browser. You will need a random number generator, because you know that procedural game content means infinite amount of fun. But you are a functional programmer, so Math.random is not good enough. No way to replay.

You find a simple algorithm, you think that would be easy to implement. Oh noes, you realise: there are no proper fixed width integers in JavaScript, all numbers are IEEE-754 doubles underneath. Your implementation works, but produces some not-random-enough garbage!

Luckily code is data, data is code. Let's write a little macro. It will take a piece of data, which looks like simple arithmetic and bit-wiggling code; do some transformations, like: make it correct and maybe even faster, and give it back to the outer compiler.

Once you have written a compiler, you'll never miss an opportunity to write another one. I'll show you how to write a very small compiler, but an optimising one. It would be lie to say it will fit on the slide; but it will fit in the deck.