Execute HQ9+

From Rosetta Code
Revision as of 17:31, 25 March 2010 by Rdm (talk | contribs) (make J's hq9+ accumulator persistent)
Task
Execute HQ9+
You are encouraged to solve this task according to the task description, using any language you may know.

Implement a HQ9+ interpreter or compiler for Rosetta Code.

Common Lisp

See RCHQ9+/Common Lisp.

E

See RCHQ9+/E.

Haskell

See RCHQ9+/Haskell.

J

From 99 Bottles of Beer <lang J>bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_ bobw=: bob , ' on the wall'"_ beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , bobw@<:</lang>

The rest of the interpreter: <lang J>H=: smoutput bind 'Hello, world!' Q=: smoutput @ [ hq9=: smoutput @: (beer"0) bind (1+i.-99) hqp=: (A=:1)1 :'0 0$A=:A+m[y'@]

hq9p=: H`H`Q`Q`hq9`hqp@.('HhQq9+' i. ])"_ 0~</lang>

Example use:

<lang J> hq9p 'hqQQq' Hello, world! hqQQq hqQQq hqQQq hqQQq</lang>

Java

See RCHQ9+/Java.

JavaScript

The function below executes a HQ9+ program and returns the program output as a string. <lang javascript>function hq9plus(code) {

 var out = ;
 var acc = 0;
 
 for (var i=0; i<code.length; i++) {
   switch (code.charAt(i)) {
     case 'H': out += "hello, world\n"; break;
     case 'Q': out += code + "\n"; break;
     case '9':
       for (var j=99; j>1; j--) {
         out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n";
         out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n";
       }
       out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
           "Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
           "No more bottles of beer on the wall, no more bottles of beer.\n" +
           "Go to the store and buy some more, 99 bottles of beer on the wall.\n";
       break;
     case '+': acc++; break;
   }
 }
 return out;

}</lang>

Python

See RCHQ9+/Python.

Ruby

See RCHQ9+/Ruby.

Tcl

See RCHQ9+/Tcl.

Ursala

See RCHQ9+/Ursala.