Skip to content

Instantly share code, notes, and snippets.

@bruinbrown
Created February 24, 2014 21:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bruinbrown/9197066 to your computer and use it in GitHub Desktop.
Save bruinbrown/9197066 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in F#. Matches most of the functionality of https://github.com/bruinbrown/Brainfuck-Interpreter but it's in F# instead of C#
let FindJump dir (program:char []) cidx =
let s = System.Collections.Generic.Stack<int>()
let rec NextChar index =
match program.[index], dir with
| '[', 1
| ']', -1 -> s.Push(index)
NextChar (index+dir)
| ']', 1
| '[', -1 -> if s.Count = 0 then (index+1)
else
s.Pop() |> ignore
NextChar (index+dir)
| _ -> NextChar (index+dir)
NextChar (cidx+dir)
let FindForwardJump = FindJump 1
let FindBackwardJump = FindJump -1
let rec Execute (program:string) ip dp (data:int []) =
if ip = program.Length then ()
else
match program.[ip] with
| '>' -> Execute program (ip+1) (dp+1) data
| '<' -> Execute program (ip+1) (dp-1) data
| ',' -> let k = System.Console.ReadKey().KeyChar |> int
data.[dp] <- k
Execute program (ip+1) dp data
| '.' -> printf "%c" (data.[dp] |> char)
Execute program (ip+1) dp data
| '+' -> do data.[dp] <- data.[dp] + 1
Execute program (ip+1) dp data
| '-' -> do data.[dp] <- data.[dp] - 1
Execute program (ip+1) dp data
| '[' -> let idx = if data.[dp] = 0 then (FindForwardJump (program.ToCharArray()) ip) else (ip+1)
Execute program idx dp data
| ']' -> let idx = if data.[dp] <> 0 then (FindBackwardJump (program.ToCharArray()) ip) else (ip+1)
Execute program idx dp data
| _ -> Execute program (ip+1) dp data
let Run program = Execute program 0 0 (Array.zeroCreate 256)
let p = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment