[erlang-questions] Why use -record() ?

Jack Tang himars@REDACTED
Sun Jun 2 13:33:57 CEST 2019


Yes, `state` can be any data structure of erlang, and `record` is another
form of `tuple`. `-record(state....` equals to `{state, ....}`
I prefer record to tuple in some cases because the element can be
matched/retrieved without considering the order. the example:

`#state{refs = Refs} = State`,

do the same thing using tuple, you should take care of the order and must
fully matched

{_, _, Ref, _, _} = State

-Jack

On Sun, Jun 2, 2019 at 6:25 PM I Gusti Ngurah Oka Prinarjaya <
okaprinarjaya@REDACTED> wrote:

> Hi,
>
> I still learn Erlang OTP from learnyousomeerlang.com especially part
> https://learnyousomeerlang.com/building-applications-with-otp .
>
> Let's see code below:
>
> -module(ppool_serv).
> -behaviour(gen_server).
> ....
> ....
> -record(state, {limit=0, sup, refs, queue=queue:new()}).
> ....
> ....
> init({Limit, MFA, Sup}) ->
>   self() ! {start_worker_supervisor, Sup, MFA},
>
>   %% why using -record here for state holder?
>   {ok, #state{limit=Limit, refs=gb_sets:empty()}}.
>
> From the code above, why using record to hold state?
>
> Other than using record we also can use tuple right? Let's see alternative
> code below
>
> -module(ppool_serv).
> -behaviour(gen_server).
> ....
> ....
> ....
> init({Limit, MFA, Sup}) ->
>   self() ! {start_worker_supervisor, Sup, MFA},
>
>   Refs = gb_sets:empty(),
>   Queue = queue:new(),
>   Spv = undefined,
>   State = {Limit, Spv, Refs, Queue},
>
>   {ok, State}.
> ...
> ...
> ...
> handle_call({run, Args}, _From, {Limit, Spv, Refs, Queue}) when N > 0 ->
>   {ok, Pid} = supervisor:start_child(Spv, Args),
>   Ref = erlang:monitor(process, Pid),
>   NewRefs = gb_sets:add(Ref, Refs),
>   NewState = {Limit-1, Spv, NewRefs, Queue},
>   {reply, {ok, Pid}, NewState};
>
> We also can use the above alternative code right?
>
> Please enlightenment
>
>
> Thank you
>
>
>
>
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>


-- 
Jack Tang


http://www.linkedin.com/in/jacktang
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190602/da565b6b/attachment.htm>


More information about the erlang-questions mailing list