Created
June 15, 2013 15:23
-
-
Save bencz/5788472 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.IO | |
| open System.Collections.Generic | |
| let args = Environment.GetCommandLineArgs() | |
| if args.Length <> 2 then Environment.Exit(1) | |
| let bf = File.ReadAllText(args.[1]) | |
| let loop = Array.zeroCreate<int>(bf.Length) | |
| let stack = Stack<int>() | |
| for i = 0 to bf.Length - 1 do | |
| match bf.[i] with | |
| | '[' -> stack.Push(i) | |
| | ']' -> let start = stack.Pop() | |
| loop.[start] <- i | |
| loop.[i] <- start | |
| | _ -> () | |
| let mem = Array.zeroCreate<byte>(30000) | |
| let mutable pc, ptr = 0, 0 | |
| while pc < bf.Length do | |
| match bf.[pc] with | |
| | '+' -> mem.[ptr] <- mem.[ptr] + byte(1) | |
| | '-' -> mem.[ptr] <- mem.[ptr] - byte(1) | |
| | '<' -> ptr <- ptr - 1 | |
| | '>' -> ptr <- ptr + 1 | |
| | '.' -> Console.Write(char(mem.[ptr])) | |
| | ',' -> mem.[ptr] <- byte(Console.Read()) | |
| | '[' -> if mem.[ptr] = byte(0) then pc <- loop.[pc] | |
| | ']' -> pc <- loop.[pc] - 1 | |
| | _ -> () | |
| pc <- pc + 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment