Download:
child 37:674e9537b6ab
parent 35:1963573a943e
36:4d40c4b8e8b0
Anton Shestakov <engored@ya.ru>, Mon, 03 Mar 2014 20:00:26 +0900
Move parse_rules and winning_hand to rps_rules.

2 файлов изменено, 38 вставок(+), 23 удалений(-) [+]
src/rps3.erl file | annotate | diff | comparison | revisions
src/rps_rules.erl file | annotate | diff | comparison | revisions
--- a/src/rps3.erl Mon Mar 03 19:46:02 2014 +0900
+++ b/src/rps3.erl Mon Mar 03 20:00:26 2014 +0900
@@ -8,21 +8,9 @@
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-parse_rules([V1,Label,V2|T], #state{hands=Hands, beats=Beats, loses=Loses, why=Why}) ->
- Acc = #state{
- hands=[V1|Hands],
- beats=dict:append(V1, V2, Beats),
- loses=dict:append(V2, V1, Loses),
- why=dict:store({V1, V2}, Label, Why)},
- parse_rules([V2|T], Acc);
-
-parse_rules([_V2], Acc) ->
- Acc.
-
init([]) ->
Text = "scissors cut paper covers rock crushes scissors",
- Tokens = lists:map(fun list_to_atom/1, string:tokens(Text, " ")),
- {ok, parse_rules(Tokens, #state{})}.
+ {ok, rps_rules:parse(Text)}.
handle_call(get_hands, _From, State=#state{hands=Hands}) ->
{reply, Hands, State};
@@ -34,16 +22,7 @@
% rock, rock, paper -> paper
handle_call({winning_hand, Hands}, _From, State) ->
- HSet = sets:from_list(Hands),
- WHand = sets:fold(
- fun(Hand, Acc) ->
- Loses = dict:fetch(Hand, State#state.loses),
- case sets:is_disjoint(sets:from_list(Loses), HSet) of
- false -> Acc;
- true -> Hand
- end
- end, undefined, HSet),
- {reply, WHand, State};
+ {reply, rps_rules:winning_hand(Hands, State), State};
handle_call({why, H1, H2}, _From, State=#state{why=Why}) ->
{reply, dict:fetch({H1, H2}, Why), State}.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/rps_rules.erl Mon Mar 03 20:00:26 2014 +0900
@@ -0,0 +1,36 @@
+-module(rps_rules).
+-export([parse/1, winning_hand/2]).
+
+-record(state, {hands=[], beats=dict:new(), loses=dict:new(), why=dict:new()}).
+
+parse(Text) ->
+ Tokens = lists:map(fun list_to_atom/1, string:tokens(Text, " ")),
+ parse(Tokens, #state{}).
+
+parse([V1,Label,V2|T], #state{hands=Hands, beats=Beats, loses=Loses, why=Why}) ->
+ Acc = #state{
+ hands=[V1|Hands],
+ beats=dict:append(V1, V2, Beats),
+ loses=dict:append(V2, V1, Loses),
+ why=dict:store({V1, V2}, Label, Why)},
+ parse([V2|T], Acc);
+
+parse([_V2], Acc) ->
+ Acc.
+
+% winner for 3 hands is:
+% rock, rock, rock -> rock
+% rock, paper, scissors -> undefined
+% rock, paper, paper -> paper
+% rock, rock, paper -> paper
+
+winning_hand(Hands, State=#state{}) ->
+ HSet = sets:from_list(Hands),
+ sets:fold(
+ fun(Hand, Acc) ->
+ Loses = dict:fetch(Hand, State#state.loses),
+ case sets:is_disjoint(sets:from_list(Loses), HSet) of
+ false -> Acc;
+ true -> Hand
+ end
+ end, undefined, HSet).