Skip to content

Instantly share code, notes, and snippets.

@elbrujohalcon
Last active October 7, 2017 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elbrujohalcon/d802a33baa5e51c384009f38df85e97c to your computer and use it in GitHub Desktop.
Save elbrujohalcon/d802a33baa5e51c384009f38df85e97c to your computer and use it in GitHub Desktop.
Examples for my Blog
-module(kvs).
-behavior(gen_server).
-export([start/0, store/2, retrieve/1]).
-export([init/1, handle_call/3, handle_cast/2]).
-type from() :: {pid(), Tag :: term()}. %% gen_server doesn't export a from/0 type
-type key() :: atom().
-type value() :: term().
-type data() :: #{key() => value()}.
-type state() :: #{data := data()}.
-export_type([key/0, value/0]).
-spec start() -> {ok, pid()} | {error, term()}.
start() -> gen_server:start({local, ?MODULE}, ?MODULE, #{}, []).
-spec store(key(), value()) -> ok.
store(K, V) -> gen_server:cast(?MODULE, {store, K, V}).
-spec retrieve(key()) -> notfound | value().
retrieve(K) -> gen_server:call(?MODULE, {retrieve, K}).
-spec init(map()) -> {ok, state()}.
init(#{}) -> {ok, #{data => #{}}}.
-spec handle_cast({store, key(), value()}, state()) -> {noreply, state()}.
handle_cast({store, K, V}, State = #{data := Data}) ->
{noreply, State#{data := Data#{K => V}}}.
-spec handle_call({retrieve, key()}, from(), state()) ->
{reply, notfound | value(), state()}.
handle_call({retrieve, K}, _From, State = #{data := Data}) ->
{reply, maps:get(K, Data, notfound), State}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment