Last active
March 15, 2016 01:44
-
-
Save renatorozas/7072bae94484c42f02b3 to your computer and use it in GitHub Desktop.
Getting started with EUnit (Part 1)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(kv_db). | |
-type db() :: []. | |
-type results() :: nonempty_list({Key::atom(), Value::term()}). | |
-type err() :: {'error', string()}. | |
-export_type([db/0, results/0, err/0]). | |
-export([new/0, put/3, get/2, delete/2]). | |
-spec new() -> db(). | |
new() -> []. | |
-spec put(Key::atom(), Value::term(), Db::db()) -> results(). | |
put(Key, Value, []) when is_atom(Key) -> | |
[{Key, Value}]; | |
put(Key, Value, [{Key, _} | Db]) when is_atom(Key) -> | |
[{Key, Value} | Db]; | |
put(Key, Value, [Current | Db]) when is_atom(Key) -> | |
[Current | put(Key, Value, Db)]. | |
-spec get(Key::atom(), Db::db()) -> term() | err(). | |
get(Key, []) when is_atom(Key) -> | |
{error, "Key not found: " ++ atom_to_list(Key)}; | |
get(Key, [{Key, Value} | _]) when is_atom(Key) -> | |
Value; | |
get(Key, [_ | Db]) when is_atom(Key) -> | |
get(Key, Db). | |
-spec delete(Key::atom(), Db::db()) -> (results() | nil()) | err(). | |
delete(Key, []) -> | |
{error, "Key not found: " ++ atom_to_list(Key)}; | |
delete(Key, [{Key, _Value} | Db]) -> | |
Db; | |
delete(Key, [Tuple | Db]) -> | |
[Tuple | delete(Key, Db)]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment