1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
-module(tuple).
-compile(no_auto_import).
-include_lib("eunit/include/eunit.hrl").
-export([new/2, first/1, second/1, swap/1, fetch/2]).
new(A, B) ->
{A, B}.
-ifdef(TEST).
new_test() ->
expect:equal(new(1, 2), {1, 2}),
expect:equal(new(2, <<"3">>), {2, <<"3">>}).
-endif.
first(Tup) ->
{A, _} = Tup,
A.
-ifdef(TEST).
first_test() ->
expect:equal(first({1, 2}), 1).
-endif.
second(Tup) ->
{_, A} = Tup,
A.
-ifdef(TEST).
second_test() ->
expect:equal(second({1, 2}), 2).
-endif.
swap(Tup) ->
{A, B} = Tup,
{B, A}.
-ifdef(TEST).
swap_test() ->
expect:equal(swap({1, <<"2">>}), {<<"2">>, 1}).
-endif.
fetch(Haystack, Needle) ->
list:find(Haystack, fun(Tuple) -> case first(Tuple) =:= Needle of
true ->
{ok, second(Tuple)};
false ->
{error, []}
end end).
-ifdef(TEST).
fetch_test() ->
Proplist = [{0, <<"1">>}, {1, <<"2">>}],
expect:equal(fetch(Proplist, 0), {ok, <<"1">>}),
expect:equal(fetch(Proplist, 1), {ok, <<"2">>}),
expect:is_error(fetch(Proplist, 2)).
-endif.
|