Execute HQ9+: Difference between revisions

Content added Content deleted
No edit summary
Line 299:
<lang Erlang>% hq9+ Erlang implementation (JWL)
% http://www.erlang.org/
 
-module(hq9p).
-export([main/1]).
 
hello() ->
%% Helper function printing bottles
_ -> io:format("Hello world!~w bottles n", [N]).
bottle(N) ->
case N of
1 -> io:format("One bottle ");
_ -> io:format("~w bottles ", [N])
end.
 
prog(Prog) ->
%% Implementation of machine instructions
io:format("~s~n", [Prog]).
 
hellobottle(0) ->
io:format("HelloNo more bottles of beer world!~n").;
 
bottle(N1) ->
1 -> io:format("One1 bottle of beer ");
 
bottle(N) when N > 0 ->
prog(Prog) ->
io:format("~s~nw bottles of beer ", [ProgN]).
beer(0) ->
bottle(N-10), io:format("of beer on the wall~n"),
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");
bottle(0), io:format("on the wall~nGo to the store and buy some more~n"),
io:format("99 bottles of beer on the wall.~n");
beer(N) ->
bottle(N), io:format("on the wall~n"),
bottle(N), io:format("of~nTake one down beerand onpass theit wallaround~n"),
bottle(N-1), io:format("ofon beerthe wall~nTake one down and pass it aroundn~n"),
beer(N-1).
bottle(N-1), io:format("of beer on the wall~n"),
beer(N-1).
 
inc(Acc) ->
Acc+1.
 
%% Execute a single instruction
 
execute(Instruction, Prog, Acc) ->
case Instruction of
$H -> hello(), Acc;
$Q -> prog(Prog), Acc;
$9 -> beer(99), Acc;
$+ -> inc(Acc);
_ -> io:format("Invalid instruction: ~c~n", [Instruction]), Acc
end.
Acc
end.
 
%% Empty program, Program string, Accu
main([], _Prog, Acc) ->
Acc;
 
%% Instruction, Rest of program, Program string, Accu
main([Instruction | Rest], Prog, Acc) ->
NewAcc = execute(Instruction, Prog, Acc),
main(Rest, Prog, NewAcc).
 
%% Compile and execute
main(Prog) ->
Compiled = string:to_upper(Prog),
main(Compiled, Prog, 0).
 
}</lang>
 
}</lang>
 
=={{header|Forth}}==