Examples

This page contains examples of some popular algorithms implemented as Bedrock programs. Click on a code block to run it in the browser.

Fibonacci sequence

Calculate and return the nth element of the Fibonacci sequence, keeping the result on the working stack. Change the value at the start of the first line and re-run the program.

The core of the function is the instruction sequence SWP* OVR* ADD*. This takes the two values a b and changes them to the values b a+b.

:05 JMS:fibonacci HLT

( Return the nth fibonacci number. )
@fibonacci  ( n -- fib* )
  PSHr *:0000 *:0001
  &loop  ( a* b* | n )
    SWP* OVR* ADD*
    DECr DUPr JCNr:~loop
  SWP* POP* POPr JMPr

Fizzbuzz

Print the first n entries of the fizzbuzz sequence. fizz is printed if n is divisible by 3, buzz if divisible by 5, fizzbuzz if divisible by 15, or the number by itself otherwise.

%CALL:   JMS:   ;
%ELSE:   JCN:   ;
%RETURN  JMPr   ;
%λ:      JMSr:  ;
%BOOL    GTH:00 ;
%DIV     STD:23 STD:21 LDD:2D ;
%MOD     STD:23 STD:21 LDD:2F ;

( Print the first 32 numbers. )
:20 CALL:fizzbuzz HLT

@fizzbuzz ( n -- )
  :00 &loop ( end i -- )
    INC
    DUP :03 MOD BOOL DUP ELSE:{ λ:{"fizz"} CALL:print-string }
    OVR :05 MOD BOOL DUP ELSE:{ λ:{"buzz"} CALL:print-string }
    AND NOT ELSE:{ DUP CALL:print-decimal }
    :0A STD:86 NQK JCN:~loop
  POP* RETURN

@print-decimal  ( n -- )
  DUP :0A DIV CALL:~print-digit :0A MOD
  &print-digit ADD:30 STD:86 RETURN

@print-string  ( addr* -- )
  DUP* LDA STD:86 INC*
  DUP* LDA JCN:print-string
  POP* RETURN