Skip to content

Instantly share code, notes, and snippets.

@hpyhacking
Created February 17, 2012 15:26
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 hpyhacking/1854019 to your computer and use it in GitHub Desktop.
Save hpyhacking/1854019 to your computer and use it in GitHub Desktop.
Erlang Programming Chapter II
-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).
-module(every).
-export([add_one/1, avg/1, even/1, member/2, sum_acc/2, bump/2]).
add_one([]) -> [];
add_one([H|T]) -> [H + 1 | add_one(T)].
%bump([], List) -> reverse(List);
bump([H|T], List) -> bump(T, [H+1|List]).
avg(List) -> sum(List) / len(List).
sum([]) -> 0;
sum([H|T]) -> H + sum(T).
len([]) -> 0;
len([_|T]) -> 1 + len(T).
even([]) -> [];
even([Head | Tail]) when Head rem 2 == 0 -> [Head | even(Tail)];
even([_ | Tail]) -> even(Tail).
member(_, []) -> false;
member(Item, [H|_]) when Item == H -> true;
member(Item, [_|T]) -> member(Item, T).
sum_acc([], Sum) -> Sum;
sum_acc([H|T], Sum) -> sum_acc(T, Sum + H).
-module(exec).
-export([sum/1, sum/2, create/1]).
sum(1) -> 1;
sum(I) when I > 0 -> I + sum(I - 1);
sum(_) -> {error, "less one"}.
sum(N, M) when N > M -> exit("N > M");
sum(N, N) -> N;
sum(N, M) -> N + sum(N + 1, M).
create(0) -> [];
create(C) when C > 0 -> [C | create(C - 1)].
-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, []).
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]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment