Comment

Comment by gamegoblin

Are there any common languages that allow you to do compile time metaprogramming in the language itself? I'd like to write little miniprograms which output source code and get evaluated at compile time. For example:

    #include <stdio.h>
    #include <stdlib.h>

    #COMPILETIME
    
    int fib(int n) {
        if(n < 2) return n;
        return fib(n-1) + fib(n-2);
    }

    int main() {
        printf("int fib(int n) {\n");
        printf("    switch(n) {\n");
        for(int i=0; i < 30; i++) {
            printf("case %d: return %d\n", i, fib(i));
        }
        printf("default: return fib(n-1) + fib(n-2);\n");
        printf("}\n}");
    }

    #ENDCOMPILETIME
and then at compile time that would get run and the source could generated would be:

    int fib(int n) {
        switch(n) {
        case 0: return 0;
        case 1: return 1;
        case 2: return 1;
        case 3: return 2;
        case 4: return 3;
        case 5: return 5;
        case 6: return 8;
        ... etc up to i=29...
        default: return fib(n-1) + fib(n-2);
        }
    }
parent gamegoblin 11 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton