· 9 years ago · Nov 01, 2016, 09:02 AM
1-module(solution).
2-export([main/0]).
3
4main() ->
5 printContacts(sortContacts(filterContacts(createContacts(readAll())))).
6
7readAll() ->
8 readAll([], io:get_chars("", 4096)).
9readAll(In, eof) ->
10 [StringN|Lines] = string:tokens(lists:flatten(lists:reverse(In)), "\n"),
11 {list_to_integer(StringN), Lines};
12readAll(In, Data) ->
13 readAll([Data|In], io:get_chars("", 4096)).
14
15createContacts({N, Entries}) ->
16 createContacts({N, Entries}, []).
17createContacts({0, _Entries}, PhoneBook) ->
18 PhoneBook;
19createContacts({N, [Entry|Lines]}, PhoneBook) ->
20 [Key, Value] = string:tokens(Entry, " "),
21 createContacts({N-1, Lines}, lists:append([{Key, Value}], PhoneBook)).
22
23filterContacts(Contacts) ->
24 filterContacts(Contacts, []).
25
26filterContacts([], Out) ->
27 Out;
28filterContacts([{Firstname, Email} | In], Out) ->
29 case re:run(Email, "@gmail.com$") of
30 {match, _} -> filterContacts(In, [Firstname | Out]);
31 nomatch -> filterContacts(In, Out)
32 end.
33
34sortContacts(Contacts) ->
35 lists:sort(Contacts).
36
37printContacts(Contacts) ->
38 lists:foreach(fun(Contact) -> io:fwrite("~s~n", [Contact]) end, Contacts).