Task

Implement a    HQ9+    interpreter or compiler.




with javascript_semantics
-- copied from 99_Bottles_of_Beer
constant ninetynine = 2 -- (set this to 9 for testing)

function bottles(integer count)
    if count=0 then     return "no more bottles"
    elsif count=1 then  return "1 bottle" end if
    if count=-1 then count = ninetynine end if
    return sprintf("%d bottles",count)
end function

function bob(integer count)
    return bottles(count)&" of beer"
end function

function up1(string bob)
-- Capitalise sentence start (needed just the once, "no more"=>"No more")
    bob[1] = upper(bob[1])
    return bob
end function

procedure ninetyninebottles()
    string thus = bob(ninetynine),
           that = "Take one down, pass it around,\n"
    for i=ninetynine to 0 by -1 do
        puts(1,up1(thus)&" on the wall,\n")
        puts(1,thus&".\n")
        if i=0 then that = "Go to the store, buy some more,\n"
        elsif i=1 then that[6..8] = "it" end if
        thus = bob(i-1)
        puts(1,that&thus&" on the wall.\n\n")
    end for
--  if getc(0) then end if
end procedure

-- the interpreter

procedure hq9(string code)
    integer accumulator = 0
    for i=1 to length(code) do
        switch(upper(code[i]))
            case 'H': printf(1,"Hello, world!\n")
            case 'Q': printf(1,"%s\n", code);
            case '9': ninetyninebottles()
            case '+': accumulator += 1
        end switch
    end for
end procedure

hq9("h9+HqQ+Qq")
