Execute HQ9+: Difference between revisions
Content added Content deleted
No edit summary |
No edit summary |
||
Line 321: | Line 321: | ||
%% Helper function printing bottles |
%% Helper function printing bottles |
||
bottle(N) -> |
bottle(N) -> |
||
case N of |
|||
1 -> io:format("One bottle "); |
|||
_ -> io:format("~w bottles ", [N]) |
|||
end. |
|||
%% Implementation of machine instructions |
%% Implementation of machine instructions |
||
hello() -> |
hello() -> |
||
io:format("Hello world!~n", []). |
|||
prog(Prog) -> |
prog(Prog) -> |
||
io:format("~s~n", [Prog]). |
|||
beer(0) -> |
beer(0) -> |
||
io:format("No more bottles of beer on the wall~nNo more bottles of beer on the wall~nGo to the store and buy some more~n99 bottles of beer on the wall.~n"); |
|||
beer(N) -> |
beer(N) -> |
||
io:format("~n"), |
|||
bottle(N), io:format("of beer on the wall~n"), |
bottle(N), io:format("of beer on the wall~n"), |
||
bottle(N), io:format("of beer~nTake one down and pass it around~n"), |
|||
bottle(N-1), io:format("of beer on the wall~n"), |
bottle(N-1), io:format("of beer on the wall~n"), |
||
beer(N-1). |
beer(N-1). |
||
inc(Acc) -> |
inc(Acc) -> |
||
Acc+1. |
|||
%% Execute a single instruction |
%% Execute a single instruction |
||
execute(Instruction, Prog, Acc) -> |
execute(Instruction, Prog, Acc) -> |
||
case Instruction of |
|||
$H -> hello(), Acc; |
|||
$Q -> prog(Prog), Acc; |
|||
$9 -> beer(99), Acc; |
|||
$+ -> inc(Acc); |
|||
_ -> io:format("Invalid instruction: ~w", [Instruction]), |
|||
Acc |
|||
end. |
|||
%% Empty program, Program string, Accu |
%% Empty program, Program string, Accu |
||
main([], _Prog, Acc) -> |
main([], _Prog, Acc) -> |
||
Acc; |
|||
%% Instruction, Rest of program, Program string, Accu |
%% Instruction, Rest of program, Program string, Accu |
||
main([Instruction | Rest], Prog, Acc) -> |
main([Instruction | Rest], Prog, Acc) -> |
||
NewAcc = execute(Instruction, Prog, Acc), |
|||
main(Rest, Prog, NewAcc). |
|||
%% Compile and execute |
%% Compile and execute |
||
main(Prog) -> |
main(Prog) -> |
||
Compiled = string:to_upper(Prog), |
|||
main(Compiled, Prog, 0). |
main(Compiled, Prog, 0). |
||
}</lang> |
}</lang> |
||