Brainfuck as (g)forth Embedded Domain-Specific Language (EDSL). Why is this interesting? When writing a Brianfuck interpreter, the implementation language has to simulate the structures of the Brainfuck; there's a stack used to handle the nested loops, programs are strings of tokens with a pointer as a program counter.
Instead, embedding Brainfuck means that the programs and control structures are the same as those used by the implementation language.
In Forth, you can define +
and [
to be functions like any other.
Looping constructs can just be aliases for Forth's looping structures.
The result is a very terse Brainfuck implementation:
VARIABLE ARRAY 1000 CELLS ALLOT
ARRAY 1000 0 FILL
VARIABLE APTR
ARRAY APTR !
: RESET
ARRAY 1000 0 FILL
ARRAY APTR !
;
: PEEK APTR @ @ ;
: POKE APTR @ ! ;
: < APTR @ 1 CELLS - APTR ! ;
: > APTR @ 1 CELLS + APTR ! ;
: + PEEK 1+ POKE ;
: - PEEK 1- POKE ;
: . PEEK . ;
: , KEY POKE ;
: [ POSTPONE BEGIN POSTPONE PEEK POSTPONE WHILE ; IMMEDIATE
: ] POSTPONE REPEAT ; IMMEDIATE
\ example programs:
: echo , [ . , ] ;
: add , > , [ < + > - ]