Voting

Category

real language

Bookmarking

Del.icio.us Digg Diigo DZone Earthlink Google Kick.ie
Windows Live LookLater Ma.gnolia Reddit Rojo StumbleUpon Technorati

Language D

(Template metaprogramming)

Date:07/11/06
Author:Don Clugston
URL:n/a
Comments:1
Info:http://www.digitalmars.com/d
Score: (3.01 in 259 votes)
// Displays the "99 bottles of beer" song at compile time,
// using the template metaprograming facilities of D. 
// No executable is generated. No libraries are used.
// Illustrates template default values, template string value parameters,
// compile-time concatenation of constant strings, static if.

template decimaldigit(int n) {
    const char [] decimaldigit = "0123456789"[n..n+1];
}

template itoa(ulong n)
{
    static if ( n < 10L )
	const char [] itoa = decimaldigit!(n);
    else
	const char [] itoa = itoa!( n / 10L ) ~ decimaldigit!( n % 10L );
}

template showHowMany(int n, char [] where, bool needcapital = false)
{
  static if ( n > 1 ) 
      const char [] showHowMany = itoa!(n) ~ " bottles of beer" ~ where ~ \n;
  else static if ( n == 1 )
      const char [] showHowMany = "1 bottle of beer" ~ where ~ \n;
  else static if ( needcapital )
      const char [] showHowMany = "No more bottles of beer" ~ where ~ \n;
  else 
      const char [] showHowMany = "no more bottles of beer" ~ where ~ \n;
}

template beer(int maxbeers, int n = maxbeers)
{
  static if ( n > 0 )
    const char [] beer = showHowMany!(n, " on the wall,", true)
        ~ showHowMany!(n, ".")
        ~ "Take one down and pass it around, " \n 
        ~ showHowMany!( n - 1 , " on the wall.") 
        ~ \n ~ beer!(maxbeers, n - 1); // recurse for subsequent verses.
  else
    const char [] beer = showHowMany!(n, " on the wall,", true)
        ~ showHowMany!(n, ".")
        ~ "Go to the store and buy some more, " \n
        ~ showHowMany!( maxbeers, " on the wall.");
}

pragma(msg, beer!(99));

Download Source | Write Comment

Alternative Versions

VersionAuthorDateCommentsRate
1Stewart Gordon05/31/054
D feuture's galoreFredrik Olsson10/09/052
Fiber "Ring"Bryan Knowles11/17/100
Div Operator Editionbadmadevil02/29/080
5Philipp Winterberg04/20/057

Comments

>>  Gregor Richards said on 08/15/06 19:45:01

Gregor Richards This is the most awesome code ever. Mix this with a runtime 99-bob and that is one extreme 99bob.d ^^

Download Source | Write Comment

Add Comment

Please provide a value for the fields Name, Comment and Security Code.
This is a gravatar-friendly website.
E-mail addresses will never be shown.
Enter your e-mail address to use your gravatar.

Please don't post large portions of code here! Use the form to submit new examples or updates instead!

Name:

eMail:

URL:

Security Code:
  
Comment: