Brainfuck interpreter in Nimrod
Asked Answered
E

1

8

I am toying with nim (at the time of writing still called nimrod), by writing a Brainfuck interpreter in the language. Without loops implemented, I have:

import os, unsigned

const RamSize = 200

type
  TRam = array[0..RamSize, int]

var
  ram : TRam
  ip  : int = 0
  dp  : int = 0

proc readCode(path: string) =
  var
    f : TFile = open(path)
    i : int = 0
  while i < RamSize and not EndOfFile(f):
    ram[i] = ord(readChar(f))
    inc(i)

proc main(path: string) =

  readCode(path)
  while ip < RamSize:
    case chr(ram[ip])
    of '>' : inc dp
    of '<' : dec dp
    of '+' : inc ram[dp]
    of '-' : dec ram[dp]
    of '.' : write stdout, chr(ram[dp])
    else   : nil
    inc(ip)
  echo()

if paramcount() == 1: main(paramstr(1))
else: echo("usage: bfrun PATH")

It compiles successfully, but when I throw an input at it like:

>
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ .

Which should print the character 'A' it returns 'N.' Any ideas?

Expertize answered 30/5, 2013 at 17:50 Comment(0)
C
6

If I understand this correctly, it looks like dp is set to 1, and then ram[dp] is incremented 65 times. But ram[dp], aka ram[1], starts out holding the second character of the program, which is a carriage return character (ASCII 13). A is ASCII 65, N is ASCII 78, and 65 + 13 is 78.

Set dp to somewhere outside of program space before you start incrementing the memory cell -- or use separate RAM to hold the program.

Castor answered 30/5, 2013 at 18:10 Comment(1)
Great, thanks. The solution is adding another RAM "tape" to avoid the issue of incrementing on the carriage return.Expertize

© 2022 - 2024 — McMap. All rights reserved.