"Fossies" - the Fresh Open Source Software Archive

Member "ldc-1.7.0-src/tests/d2/dmd-testsuite/compilable/99bottles.d" (5 Jan 2018, 1788 Bytes) of package /linux/misc/ldc-1.7.0-src.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) D source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 // written by Don Clugston:
    2 //    http://www.digitalmars.com/d/archives/digitalmars/D/announce/4374.html
    3 //    http://www.99-bottles-of-beer.net/language-d-1212.html
    4 
    5 // Displays the "99 bottles of beer" song at compile time,
    6 // using the template metaprograming facilities of D. 
    7 // No executable is generated. No libraries are used.
    8 // Illustrates template default values, template string value parameters,
    9 // compile-time concatenation of constant strings, static if.
   10 
   11 module bottles99;
   12 
   13 template decimaldigit(int n) {
   14     const string decimaldigit = "0123456789"[n..n+1];
   15 }
   16 
   17 template itoa(ulong n)
   18 {
   19     static if ( n < 10L )
   20     const string itoa = decimaldigit!(n);
   21     else
   22     const string itoa = itoa!( n / 10L ) ~ decimaldigit!( n % 10L );
   23 }
   24 
   25 template showHowMany(int n, string where, bool needcapital = false)
   26 {
   27   static if ( n > 1 ) 
   28       const string showHowMany = itoa!(n) ~ " bottles of beer" ~ where ~ "\n";
   29   else static if ( n == 1 )
   30       const string showHowMany = "1 bottle of beer" ~ where ~ "\n";
   31   else static if ( needcapital )
   32       const string showHowMany = "No more bottles of beer" ~ where ~ "\n";
   33   else 
   34       const string showHowMany = "no more bottles of beer" ~ where ~ "\n";
   35 }
   36 
   37 template beer(int maxbeers, int n = maxbeers)
   38 {
   39   static if ( n > 0 )
   40     const string beer = showHowMany!(n, " on the wall,", true)
   41         ~ showHowMany!(n, ".")
   42         ~ "Take one down and pass it around, " ~ "\n" 
   43         ~ showHowMany!( n - 1 , " on the wall.") 
   44         ~ "\n" ~ beer!(maxbeers, n - 1); // recurse for subsequent verses.
   45   else
   46     const string beer = showHowMany!(n, " on the wall,", true)
   47         ~ showHowMany!(n, ".")
   48         ~ "Go to the store and buy some more, " ~ "\n"
   49         ~ showHowMany!( maxbeers, " on the wall.");
   50 }
   51 
   52 pragma(msg, beer!(99));