HQ9+インタープリタ

以前からHQ9+のインタープリタを書いてみようとは思ってたんだけど、実際に書いてみたらあまりにもショボくてビックリした。曲がりなりにもコンピュータ言語のインタープリタだと言うことで少々かまえ過ぎていたようだ。

以下は C++ で書いたそのHQ9+インタープリタソースコードです。

#include <stdlib.h>
#include <iostream>
#include <string>

void output_99_bottles_of_beer(std::ostream &os)
{
    const int max_bottle_count = 99;
    int bottle_counter = max_bottle_count;
    while(true)
    {
        os  << bottle_counter
            << " bottles of beer on the wall, "
            << bottle_counter << " bottles of beer."
            << std::endl;
        if (--bottle_counter <= 0)
        {
            break;
        }
        os  << "Take one down and pass it around, "
            << bottle_counter
            << " bottles of beer on the wall."
            << std::endl;
        os  << std::endl;
    }
    os  << "Take one down and pass it around, no more bottles of beer on the wall."
        << std::endl;
    os  << std::endl;
    os  << "No more bottles of beer on the wall, no more bottles of beer. "
        << std::endl;
    os  << "Go to the store and buy some more, "
        << max_bottle_count
        << " bottles of beer on the wall."
        << std::endl;
}

int main(int argc, char *args[])
{
    argc, args; // 警告避け
    while(false == std::cin.eof())
    {
        int accumulator = 0;
        std::string commandline;
        std::cin >> commandline;
        for
        (
            std::string::const_iterator i = commandline.begin();
            i != commandline.end();
            ++i
        )
        {
            switch(*i)
            {
            case 'H':
                std::cout << "Hello, world!";
                break;
                
            case 'Q':
                std::cout << commandline;
                break;
            
            case '9':
                output_99_bottles_of_beer(std::cout);
                break;
            
            case '+':
                ++accumulator;
                break;
            
            default:
                std::cerr << "Unknown command error!" << std::endl;
                return EXIT_FAILURE;
            }
        }
        accumulator; // 警告避け
        std::cout << std::endl;
    }
    return EXIT_SUCCESS;
}

HQ9+が持ってる機能ってプログラム言語の練習問題としてよくあがる課題の寄せ集めなわけですが、HQ9+ 自体もプログラミング言語の練習問題としてアリかもしれませんね。

ちなみに 99 bottles of beer ってかなり豊富にバリエーションがあるみたいで且つ"これが正式な(正しい)歌詞"ってものが無さげ。あと、bcc だと "HQ9+.exe" みたいにファイル名に "+" が含まれる実行形式ファイルの作成ができないみたい。