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 Erlang

(Concurrent solution)

Date:05/15/07
Author:Bill Clementson
URL:http://bc.tech.coop/blog
Comments:2
Info:http://www.erlang.org/
Score: (3.20 in 15 votes)
-module(beersong).
-export([sing/0]).
-define(TEMPLATE_0, "~s of beer on the wall, ~s of beer.~nGo to the store and buy some more, 99
bottles of beer on the wall.~n").
-define(TEMPLATE_N, "~s of beer on the wall, ~s of beer.~nTake one down and pass it around, ~s of
beer on the wall.~n~n").

create_verse(0)      -> {0, io_lib:format(?TEMPLATE_0, phrase(0))};
create_verse(Bottle) -> {Bottle, io_lib:format(?TEMPLATE_N, phrase(Bottle))}.

phrase(0)      -> ["No more bottles", "no more bottles"];
phrase(1)      -> ["1 bottle", "1 bottle", "no more bottles"];
phrase(2)      -> ["2 bottles", "2 bottles", "1 bottle"];
phrase(Bottle) -> lists:duplicate(2, integer_to_list(Bottle) ++ " bottles") ++
[integer_to_list(Bottle-1) ++ " bottles"].

bottles() -> lists:reverse(lists:seq(0,99)).

sing() ->
    lists:foreach(fun spawn_singer/1, bottles()),
    sing_verse(99).

spawn_singer(Bottle) ->
    Pid = self(), 
    spawn(fun() -> Pid ! create_verse(Bottle) end).

sing_verse(Bottle) ->
    receive
	{_, Verse} when Bottle == 0 ->
	    io:format(Verse);
	{N, Verse} when Bottle == N ->
	    io:format(Verse),
	    sing_verse(Bottle-1)
    after 
	3000 ->
	    io:format("Verse not received - re-starting singer~n"),
	    spawn_singer(Bottle),
	    sing_verse(Bottle)
    end.

Download Source | Write Comment

Alternative Versions

VersionAuthorDateCommentsRate
advanced with exact last verseKurt J. Bosch06/27/050
proper version - simple codeHåkan Stenholm01/23/060

Comments

>>  Bill Clementson said on 05/28/07 02:24:31

Bill Clementson My weblog entry for this post is here: http://bc.tech.coop/blog/070514.html

>>  Tom Eklöf said on 05/16/08 10:44:00

Tom Eklöf Ha, try doing that in just 39 lines with Java.

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: