RosettaCodeData/Task/Execute-Brain----/Mathematica/execute-brain-----1.math

22 lines
651 B
Text
Raw Permalink Normal View History

2013-04-12 15:51:01 -07:00
bf[program_, input_] :=
Module[{p = Characters[program], pp = 0, m, mp = 0, bc = 0,
2014-01-17 05:32:22 +00:00
instr = StringToStream[input]},
2013-10-27 22:24:23 +00:00
m[_] = 0;
While[pp < Length@p,
pp++;
Switch[p[[pp]],
">", mp++,
"<", mp--,
"+", m[mp]++,
"-", m[mp]--,
2014-01-17 05:32:22 +00:00
".", BinaryWrite["stdout", m[mp]],
2013-10-27 22:24:23 +00:00
",", m[mp] = BinaryRead[instr],
"[", If[m[mp] == 0,
bc = 1;
While[bc > 0, pp++; Switch[p[[pp]], "[", bc++, "]", bc--]]],
"]", If[m[mp] != 0,
bc = -1;
While[bc < 0, pp--; Switch[p[[pp]], "[", bc++, "]", bc--]]]]];
Close[instr];];
2013-04-12 15:51:01 -07:00
bf[program_] := bf[program, ""]