Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.

Below are links to each of the versions of RCBF.

An implementation need only properly implement the following instructions:



Command

Description


 > 
 Move the pointer to the right


 < 
 Move the pointer to the left


 + 
 Increment the memory cell under the pointer


 - 
 Decrement the memory cell under the pointer


 . 
 Output the character signified by the cell at the pointer


 , 
 Input a character and store it in the cell at the pointer


 [ 
 Jump past the matching ] if the cell under the pointer is 0


 ] 
 Jump back to the matching [ if the cell under the pointer is nonzero

Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.




-- Code based on
-- https://github.com/allisio/pointless/blob/master/lib/examples/brainfuck.ptls
 
output =
  iterate(run, vm)
  |> takeUntil(isFinished)
  |> map(vm => vm.outVal)
  |> filter(notEq(None))
  |> map(char)
  |> printElems
 
----------------------------------------------------------
 
vm = VM {
  ip = 0
  dp = 0
  data = zeroArray(1000)
  inVals = map(ord, readLines)
  outVal = None
}
 
----------------------------------------------------------
-- "hello.bf" contains brainf*** hello world code
 
ops = toArray(readFile("hello.bf"))
 
----------------------------------------------------------
 
run(vm) = vm |> clearOutput |> eval |> advance 
 
advance(vm)     = vm with $.ip += 1
isFinished(vm)  = vm.ip >= length(ops)
clearOutput(vm) = vm with $.outVal = None
 
----------------------------------------------------------
 
jumps = getJumps(0, [], {})
 
getJumps(i, stack, jumps) = cond {
  case (i == length(ops)) jumps
 
  case (ops[i] == "[")
    getJumps(i + 1, [i] ++ stack, jumps)
 
  case (ops[i] == "]")
    getJumps(i + 1, tail(stack), jumps with {
      $[i] = head(stack)   
      $[head(stack)] = i
    })
 
  else getJumps(i + 1, stack, jumps)
}
 
----------------------------------------------------------
 
eval(vm) = cond {
  case (op == ">") vm with $.dp += 1
  case (op == "<") vm with $.dp -= 1
  case (op == "+") vm with $.data[vm.dp] += 1
  case (op == "-") vm with $.data[vm.dp] -= 1
  case (op == ".") vm with $.outVal = byte
 
  case (op == ",") vm with {
    $.data[vm.dp] = head(vm.inVals)
    $.inVals = tail(vm.inVals)
  }
 
  case (op == "[")
    if byte != 0 then vm
    else (vm with $.ip = jumps[vm.ip])
 
  case (op == "]")
    if byte == 0 then vm
    else (vm with $.ip = jumps[vm.ip])
 
  else vm
 
} where {
  op = ops[vm.ip]
  byte = vm.data[vm.dp]
}