Guest User

Untitled

a guest
Aug 9th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.34 KB | None | 0 0
  1. -module(beersong).
  2. -export([sing/0]).
  3. -define(TEMPLATE_0, "~s of beer on the wall, ~s of beer.~nGo to the store and buy some more, 99
  4. bottles of beer on the wall.~n").
  5. -define(TEMPLATE_N, "~s of beer on the wall, ~s of beer.~nTake one down and pass it around, ~s of
  6. beer on the wall.~n~n").
  7.  
  8. create_verse(0)      -> {0, io_lib:format(?TEMPLATE_0, phrase(0))};
  9. create_verse(Bottle) -> {Bottle, io_lib:format(?TEMPLATE_N, phrase(Bottle))}.
  10.  
  11. phrase(0)      -> ["No more bottles", "no more bottles"];
  12. phrase(1)      -> ["1 bottle", "1 bottle", "no more bottles"];
  13. phrase(2)      -> ["2 bottles", "2 bottles", "1 bottle"];
  14. phrase(Bottle) -> lists:duplicate(2, integer_to_list(Bottle) ++ " bottles") ++
  15. [integer_to_list(Bottle-1) ++ " bottles"].
  16.  
  17. bottles() -> lists:reverse(lists:seq(0,99)).
  18.  
  19. sing() ->
  20.     lists:foreach(fun spawn_singer/1, bottles()),
  21.     sing_verse(99).
  22.  
  23. spawn_singer(Bottle) ->
  24.     Pid = self(),
  25.     spawn(fun() -> Pid ! create_verse(Bottle) end).
  26.  
  27. sing_verse(Bottle) ->
  28.     receive
  29.         {_, Verse} when Bottle == 0 ->
  30.             io:format(Verse);
  31.         {N, Verse} when Bottle == N ->
  32.             io:format(Verse),
  33.             sing_verse(Bottle-1)
  34.     after
  35.         3000 ->
  36.             io:format("Verse not received - re-starting singer~n"),
  37.             spawn_singer(Bottle),
  38.             sing_verse(Bottle)
  39.     end.
Add Comment
Please, Sign In to add comment