[erlang-questions] pattern matching registered name

Yogish Baliga yogishb@REDACTED
Mon May 20 19:48:51 CEST 2013


When you call rpc(abc, blah), Pid = abc. In your rpc(...) code you are
waiting for
{abc, Resp} in receive loop.


On Mon, May 20, 2013 at 10:12 AM, Edmund Sumbar <esumbar@REDACTED> wrote:

> Hello,
>
> I'm new to erlang and am perplexed by the use of registered names when
> they are passed as function parameters and subsequently used in pattern
> matching.
>
> For example (taken from Programming Erlang 2/ed by Joe Armstrong),
>
> -module(kvs).
> -export([start/0, rpc/1]).
>
> start() -> register(kvs, spawn(fun() -> loop() end)).
>
> rpc(Q) ->
>   kvs ! {self(), Q},
>   receive
>     {kvs, Reply} ->
>       Reply
>   end.
>
> loop() ->
>   receive
>     {From, {store, Key, Value}} ->
>       put(Key, {ok, Value}),
>       From ! {kvs, true},
>       loop();
>     {From, {lookup, Key}} ->
>       From ! {kvs, get(Key)},
>       loop()
>   end.
>
> This module works as expected.
>
> $ erl
> Erlang R16B (erts-5.10.1) [source] [64-bit] [smp:8:8] [async-threads:10]
> [hipe] [kernel-poll:false] [dtrace]
>
> Eshell V5.10.1  (abort with ^G)
> 1> c(kvs).
> {ok,kvs}
> 2> kvs:start().
> true
> 3> kvs:rpc({store, name, "Joe"}).
> true
> 4> kvs:rpc({lookup, name}).
> {ok,"Joe"}
>
> Then, I modify the code to remove the registered name.
>
> -module(kvsx).
> -export([start/0, rpc/2]).
>
> start() -> spawn(fun() -> loop() end).
>
> rpc(Pid, Q) ->
>   Pid ! {self(), Q},
>   receive
>     {Pid, Reply} ->
>       Reply
>   end.
>
> loop() ->
>   receive
>     {From, {store, Key, Value}} ->
>       put(Key, {ok, Value}),
>       From ! {self(), true},
>       loop();
>     {From, {lookup, Key}} ->
>       From ! {self(), get(Key)},
>       loop()
>   end.
>
> The modified module also works as expected.
>
> $ erl
> Erlang R16B (erts-5.10.1) [source] [64-bit] [smp:8:8] [async-threads:10]
> [hipe] [kernel-poll:false] [dtrace]
>
> Eshell V5.10.1  (abort with ^G)
> 1> c(kvsx).
> {ok,kvsx}
> 2> Pid = kvsx:start().
> <0.40.0>
> 3> kvsx:rpc(Pid, {store, name, "Joe"}).
> true
> 4> kvsx:rpc(Pid, {lookup, name}).
> {ok,"Joe"}
>
> However, when I register a name for Pid and pass it to the function, the
> process hangs.
>
> 5> register(abc, Pid).
> true
> 6> whereis(abc).
> <0.40.0>
> 7> kvsx:rpc(abc, {lookup, name}).
> ^G
> User switch command
>  --> q
>
> As a newcomer to the language (but with decades of programming
> experience), I'm confused. Can someone explain registered names and
> when/where they can be used.
>
> Ed
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130520/fc6b3816/attachment.htm>


More information about the erlang-questions mailing list