Execute Brain****/OCaml: Difference between revisions

m
Fixed syntax highlighting.
No edit summary
m (Fixed syntax highlighting.)
 
(5 intermediate revisions by 5 users not shown)
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}[[Category:OCaml]]
Quick implementation of a [[Brainfuck]] interpreter in [[OCaml]].
 
Like the [[Haskell]] [[RCBF/Haskell|version]] but without the lazy lists:
 
Pairs of lists are used to implement both the two-side infinite band of cells, and the program storage.
Line 10:
A more efficient implementation could for example only admit well-bracketed brainfuck programs, and parse bracket blocks first, to replace the ''match_left'' and ''match_right'' which need linear time.
 
<syntaxhighlight lang="ocaml">let move_left (x::l, r) = (l, x::r)
<ocaml>
let move_left (x::l, r) = (l, x::r)
let move_right (l, x::r) = (x::l, r)
 
Line 39 ⟶ 38:
 
let modify f (l, x::r) = l, f x :: r
 
let dec x =
if x = 0 then 0
else x - 1
 
let rec exec p d =
Line 54 ⟶ 49:
exec (move_right p) (modify succ d)
| (_, '-'::_), _ ->
exec (move_right p) (modify dec pred d)
| (_, ','::_), _ ->
let c = read_int () in
Line 71 ⟶ 66:
exec (match_left (move_left p)) d
 
let run s = exec ([], s) ([0], [0])</syntaxhighlight>
</ocaml>
 
Example output:
 
<pre># let char_list_of_string s =
let result = ref [] in
String.iter (fun c -> result := c :: !result) s;
List.rev !result;;
val char_list_of_string : string -> char list = <fun>
 
# run (char_list_of_string ",[>+<-].>.");;
''5''
0
5
- : unit = ()</pre>
9,476

edits