Examples

This page contains a collection 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 JMP:~start
  &loop  ( a* b* : n )
    SWP* OVR* ADD* DECr
    &start 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.

This example is longer than the Fibonacci one because we need to include functions for printing a string, printing a number, and checking if a number is a factor of another. Macros have been included at the top of the program to give readable names to the ports used.

( Assign names to device ports. )
%MATH.X      20;  %MATH.Y     22;
%MATH.QUOT   2C;  %MATH.REM   2E;
%OUT.CONTROL 83;  %OUT.STREAM 86;

*:0020 JMS:fizzbuzz HLT

( Print all fizzbuzz entries from 1 to n. )
@fizzbuzz  ( n* -- )
  *:0000 &loop  ( end* i* )
    INC* JMS:print-nth-fizzbuzz
    :00 STD:OUT.CONTROL NQK* JCN:~loop
  POP* POP* JMPr

( Print the nth fizzbuzz entry. )
@print-nth-fizzbuzz  ( n* -- n* )
  *:0003 JMS:is-factor? CPYr JCS:~print-fizz
  *:0005 JMS:is-factor? CPYr JCS:~print-buzz
  EQUr*:0000            PSH  JCN:~print-plain JMPr
  &print-fizz   *:~fizz JMP:print-string &fizz "fizz"
  &print-buzz   *:~buzz JMP:print-string &buzz "buzz"
  &print-plain     DUP* JMP:print-decimal

( Return true if f is a factor of n. )
@is-factor?  ( n* f* -- n* t? )
  OVR* STD*:MATH.X STD*:MATH.Y
  LDD*:MATH.REM EQU*:0000 JMPr

( Print null-terminated string stored at addr. )
@print-string  ( addr* -- )
  JMP:~start
  &loop  ( addr* char )
    STD:OUT.STREAM INC* &start
    DUP* LDA DUP JCN:~loop
  POP POP* JMPr

( Print n as a decimal number. )
@print-decimal  ( n* -- )
  *:000A STD*:MATH.Y r:00
  &convert  ( n* : ... )
    STD*:MATH.X LDD*:MATH.QUOT
    LDDr*:MATH.REM SWPr ADDr*:['0' 01]
    DUP* JCN*:~convert POP* POPr
  &print  ( : ... )
    STDr:OUT.STREAM
    JCNr:~print JMPr