Created
April 22, 2013 23:57
-
-
Save thelinked/5439649 to your computer and use it in GitHub Desktop.
BF interpreter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
open System.Collections.Generic | |
let brainfuck raw = | |
let code = [for c in raw -> c] |> Array.ofList | |
let memory = Array.create 1024 0 | |
let createJumpTable = | |
let mutable stack = new Stack<char*int>() | |
let mutable jumpTable = new Map<int,int>([]) | |
for i = 0 to (code.Length-1) do | |
let token = code.[i] | |
match token with | |
| '[' -> stack.Push(token,i) | |
| ']' when stack.Count > 0 && fst (stack.Peek()) = '[' -> | |
let jmp = snd (stack.Pop()) | |
jumpTable <-jumpTable.Add(i,jmp).Add(jmp,i) | |
| ']' -> failwith ("Invalid Program at " + i.ToString()) | |
| _ -> () | |
jumpTable | |
let jump = createJumpTable | |
let rec bf pc mp = | |
match code.[pc] with | |
| _ when pc >= code.Length-1 -> () | |
| '>' -> bf (pc+1) (mp+1) | |
| '<' -> bf (pc+1) (mp-1) | |
| '+' -> do memory.[mp] <- (memory.[mp]+1) | |
bf (pc+1) mp | |
| '-' -> do memory.[mp] <- (memory.[mp]-1) | |
bf (pc+1) mp | |
| '.' -> do Console.Write(char memory.[mp]) | |
bf (pc+1) mp | |
| ',' -> do memory.[mp] <- Console.Read() | |
bf (pc+1) mp | |
| '[' when memory.[mp] = 0 -> bf jump.[pc] mp | |
| ']' when memory.[mp] <> 0 -> bf jump.[pc] mp | |
| _ -> bf (pc+1) mp | |
bf 0 0 | |
let program = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." | |
brainfuck program |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment