mirror of
https://github.com/valitydev/erlang-school.git
synced 2024-11-06 09:15:17 +00:00
Add task 6 (#4)
* tasks 0,1,2,4 * fix syntax in tasks 1 and 2 * change filter to tail rec * add task 3 * fix repo? * task 5 * task 6 * last small fixes * switch to div, fix error handling
This commit is contained in:
parent
1578bc1f65
commit
223d8d2f7f
1
.gitignore
vendored
1
.gitignore
vendored
@ -2,3 +2,4 @@
|
||||
.DS_Store
|
||||
*.iml
|
||||
*.beam
|
||||
godocker.sh
|
||||
|
50
task_2_6.erl
Normal file
50
task_2_6.erl
Normal file
@ -0,0 +1,50 @@
|
||||
-module(task_2_6).
|
||||
|
||||
%% API
|
||||
-export([test/0]).
|
||||
|
||||
test() ->
|
||||
process("task_2_6.txt").
|
||||
|
||||
process(Filename) ->
|
||||
Row = readcsv(Filename),
|
||||
process_row(Row).
|
||||
|
||||
%% process_tokens
|
||||
process_row(List) ->
|
||||
process_row(List, [], List).
|
||||
|
||||
process_row([], Stack, _) ->
|
||||
lists:reverse(Stack);
|
||||
process_row([H|T], Stack, List) ->
|
||||
process_row(T, [parse_cell(H, List) | Stack], List).
|
||||
|
||||
%% parse_cell
|
||||
parse_cell(Str, List) ->
|
||||
parse_cell(string:tokens(Str, " "), [], List).
|
||||
|
||||
parse_cell([], Stack, _) ->
|
||||
case length(Stack) of
|
||||
1 -> hd(Stack);
|
||||
_ -> error(badarg)
|
||||
end;
|
||||
parse_cell([Token|Tail], Stack, List) ->
|
||||
case Token of
|
||||
"$" ++ N -> parse_cell(Tail, [parse_cell(lists:nth(list_to_integer(N), List), List) | Stack], List);
|
||||
"+" -> parse_cell(Tail, reduce(fun(A, B) -> A + B end, Stack), List);
|
||||
"-" -> parse_cell(Tail, reduce(fun(A, B) -> A - B end, Stack), List);
|
||||
"*" -> parse_cell(Tail, reduce(fun(A, B) -> A * B end, Stack), List);
|
||||
"/" -> parse_cell(Tail, reduce(fun(A, B) -> A div B end, Stack), List);
|
||||
_ -> parse_cell(Tail, [list_to_integer(Token)|Stack], List)
|
||||
end.
|
||||
|
||||
reduce(F, [A,B|Tail]) ->
|
||||
[F(B, A)|Tail];
|
||||
reduce(_, _) ->
|
||||
error(badarg).
|
||||
|
||||
readcsv(Filename) ->
|
||||
case file:read_file(Filename) of
|
||||
{ok, FileBin} -> string:tokens(erlang:binary_to_list(FileBin), ",\n");
|
||||
{error, Reason} -> error(Reason)
|
||||
end.
|
1
task_2_6.txt
Normal file
1
task_2_6.txt
Normal file
@ -0,0 +1 @@
|
||||
$5 $6 +,3,6,4,2 $2 +,2,7
|
Loading…
Reference in New Issue
Block a user