--- a/src/rps3.erl Mon Mar 03 19:46:02 2014 +0900
+++ b/src/rps3.erl Mon Mar 03 20:00:26 2014 +0900
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-parse_rules([V1,Label,V2|T], #state{hands=Hands, beats=Beats, loses=Loses, why=Why}) ->
- 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) ->
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}) ->
% rock, rock, paper -> paper
handle_call({winning_hand, Hands}, _From, State) ->
- HSet = sets:from_list(Hands),
- Loses = dict:fetch(Hand, State#state.loses),
- case sets:is_disjoint(sets:from_list(Loses), HSet) of
+ {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
+-export([parse/1, winning_hand/2]).
+-record(state, {hands=[], beats=dict:new(), loses=dict:new(), why=dict:new()}).
+ 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}) ->
+ beats=dict:append(V1, V2, Beats),
+ loses=dict:append(V2, V1, Loses),
+ why=dict:store({V1, V2}, Label, Why)},
+% 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),
+ Loses = dict:fetch(Hand, State#state.loses),
+ case sets:is_disjoint(sets:from_list(Loses), HSet) of