Skip to content

Instantly share code, notes, and snippets.

@maruks
Created June 16, 2015 08:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maruks/81e2114fbd1751727cf0 to your computer and use it in GitHub Desktop.
Save maruks/81e2114fbd1751727cf0 to your computer and use it in GitHub Desktop.
7 languages in 7 weeks: Erlang day 2
-module(dojo2).
-import(lists,[nth/2]).
-include_lib ("eunit/include/eunit.hrl").
-compile(export_all).
lookup(K,[{K,V}|_Tl]) ->
V;
lookup(K,[{_D,_V}|Tl]) ->
lookup(K, Tl);
lookup(_K,[]) ->
false.
lookup2(K,Xs) ->
{_, V} = lists:keyfind(K,1,Xs),
V.
lookup_test() ->
?assertEqual(bar, lookup(foo,[{1,2},{foo,bar},{3,4}])).
lookup_fail_test() ->
?assertEqual(false, lookup(not_present,[{1,2},{foo,bar},{3,4}])).
lookup2_test() ->
?assertEqual(bar, lookup2(foo,[{1,2},{foo,bar},{3,4}])).
basket(Xs) ->
[ {I,Q*P} || {I,Q,P} <- Xs].
basket2(Xs) ->
lists:map(fun({I,Q,P})-> {I,Q*P} end, Xs ).
basket_test() ->
?assertEqual([{apple, 10}, {mango, 12}, {milk, 18}], basket([{apple, 2,5},{mango, 3,4 },{milk, 2,9}])).
basket2_test() ->
?assertEqual([{apple, 10}, {mango, 12}, {milk, 18}], basket2([{apple, 2,5},{mango, 3,4 },{milk, 2,9}])).
winner([{X,X,X} | _Tl] )->
X;
winner([{_,_,_} | Tl] )->
winner(Tl);
winner([] )->
none.
winner0(Xs) ->
R = lists:seq(1,9),
P = [ {X,Y,Z} || X<-R, Y<-R, Z<-R, (Y==X+3 andalso Z==Y+3) ] ++
[ {X,Y,Z} || X<-[1,4,7], Y<-R, Z<-R, (Y==X+1 andalso Z==Y+1) ] ++ [{1,5,9}, {3,5,7}],
winner(lists:map(fun({A,B,C})-> {nth(A,Xs),nth(B,Xs),nth(C,Xs)} end, P)).
winner_test() ->
?assertEqual(o, winner0([o,o,o,
x,x,o,
o,x,x])).
winner2_test() ->
?assertEqual(x, winner0([x,o,x,
o,x,o,
x,o,o])).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment