Fizz-Buzz問題 その2

Erlangでもやってみた。

-module(fizz_buzz).
-export([fizz_buzz/1]).

fizz_buzz(N) ->
    fizz_buzz(N,[]).

fizz_buzz(0,L) -> L;
fizz_buzz(N,L) ->
    FizzBuzz = if
                   N rem 15 == 0 -> "FizzBuzz";
                   N rem 5  == 0 -> "Buzz";
                   N rem 3  == 0 -> "Fizz";
                   true          -> N
               end,
    fizz_buzz(N - 1, [FizzBuzz|L]).

これで僕も集(ry

gen_server化してみた。

何でもサーバにできるね。でも、これに慣れるとreceiveと!になれない。。。

-module(fizz_buzz_server).
-behaviour(gen_server).

-export([start/0, stop/0]).
-export([fizz_buzz/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
         code_change/3]).

start() -> gen_server:start({global, ?MODULE},?MODULE,[],[]).
stop() -> gen_server:cast({global, ?MODULE},stop).

fizz_buzz(N) ->
    gen_server:call({global, ?MODULE}, {fizz_buzz, N}).

init(_) -> {ok, []}.

handle_call({fizz_buzz, N}, _From, State) ->
    {reply, fizz_buzz:fizz_buzz(N), State}.

handle_cast(stop, State) -> {stop, normal, State};
handle_cast(_, State) -> {noreply, State}.

handle_info(_Info, State) -> {noreply, State}.

terminate(normal, _State) -> ok;
terminate(_, _) -> ok.

code_change(_OldVsn, StateData, _Extra) -> {ok, StateData}.