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 Scala

(Scala with a vengeance)

Date:09/16/09
Author:Eduardo Costa
URL:http://extremejava.tpk.com.br
Comments:0
Info:http://www.scala-lang.org/
Score: (3.00 in 18 votes)
/**
 * Scala implementation of "99 beers on the wall" with a vengeance. Contains
 * examples of Scala features, like tail recursion.
 *
 * @author Eduardo Costa http://extremejava.tpk.com.br
 */
object Beers extends Application {

	def bottles(qty : Int, f : => String) = // higher-order functions
		qty match {
			case 0 => "no more bottles of beer" + f
			case 1 => "1 bottle of beer" + f
			case x => x + " bottles of beer" + f
		}

	def beers(qty : Int) = bottles(qty, " on the wall.")

	def sing(qty : Int)(implicit song : String) : String = {
		def takeOne =
			qty match {
				case 0 => "Go to the store and buy some more."
				case x => "Take one down and pass it around."
			}

		def nextQty = // nested functions
			if (qty == 0) 99
			else qty - 1

		def refrain = {
			beers(qty).capitalize + " " + bottles(qty, "") + ".\n" +
			takeOne + " " + beers(nextQty) + "\n\n"
		}

		if (qty == -1) song
		else sing(qty - 1)(song + refrain) // tail recursion
	}

	implicit val headOfSong : String = ""

	println(sing(99)) // implicit parameter

}

Download Source | Write Comment

Alternative Versions

VersionAuthorDateCommentsRate
Fun semi-DSL readable versionCalum Leslie01/31/080
GrabbaBeer & CaseOfBeersD Mackenzie05/30/090
Animated versionD Mackenzie10/02/090

Comments

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: