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
Version | Author | Date | Comments | Rate |
---|---|---|---|---|
Fun semi-DSL readable version | Calum Leslie | 01/31/08 | 0 | |
GrabbaBeer & CaseOfBeers | D Mackenzie | 05/30/09 | 0 | |
Animated version | D Mackenzie | 10/02/09 | 0 |
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!
Comments