-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter.fs
47 lines (40 loc) · 1.35 KB
/
Interpreter.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
module BrainFark.Interpreter
let fromString code =
let rec skip count =
function
| c::cs ->
match c with
| '[' -> skip (count + 1) cs
| ']' ->
match count with
| 1 -> cs
| _ -> skip (count - 1) cs
| _ -> skip count cs
| [] -> failwith "unmatched ["
let rec loop mem stack =
function
| '>'::cs -> loop (Memory.moveRight mem) stack cs
| '<'::cs -> loop (Memory.moveLeft mem) stack cs
| '+'::cs -> loop (Memory.increment mem) stack cs
| '-'::cs -> loop (Memory.decrement mem) stack cs
| '.'::cs -> loop (Memory.write mem) stack cs
| ','::cs -> loop (Memory.read mem) stack cs
| '['::cs ->
match Memory.get mem with
| 0uy -> loop mem stack (skip 1 cs)
| _ -> loop mem (cs::stack) cs
| ']'::cs ->
match stack with
| s::ss ->
match Memory.get mem with
| 0uy -> loop mem ss cs
| _ -> loop mem stack s
| [] -> failwith "unmatched ["
| _::cs -> loop mem stack cs
| [] ->
match stack with
| s::ss -> failwith "unmatched ["
| _ -> mem
code
|> Seq.toList
|> (fun code mem -> loop mem [] code)