Il Fizz Buzz รจ un semplice gioco per bambini, usato spesso come primissimo test per l'assunzione di programmatori.
Ieri Gabriele Lana ci ha guidato nello svolgimento collettivo di un kata in Erlang su questo argomento. Ecco il codice prodotto.
In primo luogo i test (file fizzbuzz_tests.erl):
-module(fizzbuzz_tests).
-include_lib("eunit/include/eunit.hrl").
fizzbuzz_of_zero_should_be_zero_test() ->
?assertEqual(0, fizzbuzz:number(0)).
fizzbuzz_of_one_should_be_one_test() ->
?assertEqual(1, fizzbuzz:number(1)).
on_multiple_of_three_should_be_fizz_test_() -> [
?_assertEqual(fizz, fizzbuzz:number(3)),
?_assertEqual(fizz, fizzbuzz:number(6))
].
fizzbuzz_of_five_should_be_buzz_test_() -> [
?_assertEqual(buzz, fizzbuzz:number(5)),
?_assertEqual(buzz, fizzbuzz:number(10))
].
returns_fizzbuzz_for_multiples_of_fifteen_test_() -> [
?_assertEqual(fizzbuzz, fizzbuzz:number(15)),
?_assertEqual(fizzbuzz, fizzbuzz:number(30))
].
returns_list_of_fizzbuzzed_numbers_test_() -> [
?_assertEqual([], fizzbuzz:list([])),
?_assertEqual([0], fizzbuzz:list([0])),
?_assertEqual([0, 1, fizz], fizzbuzz:list([0, 1, 6]))
].
Ed ora il codice di "produzione" ;-) (file fizzbuzz.erl)
-module(fizzbuzz).
-export([ number/1, list/1 ]).
list(List) ->
Parent = self(),
FizzBuzzers= lists:map(fun(X) ->
TimeToSleep = random:uniform(50000),
spawn(fun() ->
timer:sleep(TimeToSleep),
Parent ! {self(), fizzbuzz:number(X)}
end)
end, List),
receive_result(FizzBuzzers).
receive_result(FizzBuzzers) ->
receive_result(FizzBuzzers, []).
receive_result([], Results) ->
Results;
receive_result([FizzBuzzer|Tail], Results) ->
receive
{FizzBuzzer, Result} -> receive_result(Tail, Results ++ [Result])
end.
number (0) -> 0;
number(Number) when Number rem 15 =:= 0 -> fizzbuzz;
number(Number) when Number rem 5 =:= 0 -> buzz;
number(Number) when Number rem 3 =:= 0 -> fizz;
number(Number) -> Number.
Comments (0)
You don't have permission to comment on this page.