Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Examples for my Blog
-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