Skip to content

Commit

Permalink
new exp
Browse files Browse the repository at this point in the history
  • Loading branch information
hpyhacking committed Jul 8, 2011
1 parent 37c062a commit ae4775b
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 3 deletions.
19 changes: 19 additions & 0 deletions chapter_3/db.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-module(db).
-export([new/0, destroy/1, write/3, delete/2, read/2, match/2]).

new() -> [].
destroy(_Db) -> successful.

write(Key, Val, Db) -> [{Key, Val} | Db].

delete(_Key, []) -> [];
delete(Key, [{HK, _}|T]) when Key == HK -> delete(Key, T);
delete(Key, [H|T]) -> [H|delete(Key, T)].

read(_Key, []) -> {error, instance};
read(Key, [{H_Key, Val}|_T]) when Key == H_Key -> {ok, Val};
read(Key, [_H|T]) -> read(Key, T).

match(_Val, []) -> [];
match(Val, [{H_Key, H_Val} | T]) when H_Val == Val -> [H_Key | match(Val, T)];
match(Val, [_H|T]) -> match(Val, T).
17 changes: 17 additions & 0 deletions chapter_3/list.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-module(list).
-compile(export_all).

filter([], _N) -> [];
filter([H|T], N) when H =< N -> [H | filter(T, N)];
filter([_H|T], N) -> filter(T, N).

reverse(List) -> reverse(List, []).

% Good Job 要多使用尾递归
reverse([], R) -> R;
reverse([H|T], R) -> reverse(T, [H|R]).

concatenate([], R) -> reverse(R);
concatenate([[]|Ty], R) -> concatenate(Ty, R);
concatenate([[H|Tx]|Ty], R) -> concatenate([Tx|Ty], [H|R]).

23 changes: 20 additions & 3 deletions chapter_3/sort.erl
Original file line number Diff line number Diff line change
@@ -1,4 +1,21 @@
-module(sort)
-export([quick/1])
-module(sort).
-compile(export_all).

qucik() -> .
quick([]) -> [];

quick([H|T]) ->
[Max, Min] = quick_x(H, T, [], []),
flatten([quick(Max) | [H | quick(Min)]]).

quick_x(_, [], Min, Max) ->
[Max, Min];

quick_x(Cur, [H|T], Min, Max) when Cur < H ->
quick_x(Cur, T, Min, [H|Max]);

quick_x(Cur, [H|T], Min, Max) when Cur >= H ->
quick_x(Cur, T, [H|Min], Max).

flatten([]) ->
flatten([H|T]) ->
[H|flatten(T)].
32 changes: 32 additions & 0 deletions chapter_4/ring.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
-module(ring).
-export([loop/1, new_proc/1, new_proc/3]).

new_proc(N) when N > 1 ->
FirstPid = spawn(ring, loop, [self()]),
new_proc(N - 1, FirstPid, FirstPid).

new_proc(0, Pid, FirstPid) ->
FirstPid ! {loop, Pid},
register(ring_srv, FirstPid),
io:format("Successful create processes");

new_proc(N, Pid, FirstPid) ->
NewPid = spawn(ring, loop, [Pid]),
new_proc(N - 1, NewPid, FirstPid).



loop(Pid) ->
receive
{loop, LastPid} ->
loop(LastPid);

{message, 1} ->
io:format("~w receive a last message ~n", [self()]),
loop(Pid);

{message, Count} ->
io:format("~w receive a message ~w -> send ~w to ~w ~n", [self(), Count, Count - 1, Pid]),
Pid ! {message, Count - 1},
loop(Pid)
end.

0 comments on commit ae4775b

Please sign in to comment.