Fw: Newbie question

kevin.hostelley@REDACTED kevin.hostelley@REDACTED
Tue Jul 21 18:45:05 CEST 2009


I'm new to erlang and I was trying to write a simple message queue to try
and learn the language.  I'm getting a result I don't understand.  Here's
the code for the program:

-module(queue).
-export([start/0, listen/1]).

listen([]) ->
    io:format("Listen with empty list.~n"),
    receive
        {get, Pid} ->
            Pid ! empty,
            listen([]);
        {put, Data} ->
            listen([Data]);
        stop ->
            io:format("Stopped.~n")
    end;

listen(Elements) ->
    io:format("Listen with current list (~s).~n", [Elements]),
    receive
        {get, Pid} ->
            [Elem|NewList] = Elements,
            Pid ! {data, Elem},
            listen(NewList);
        {put, Data} ->
            NewList2 = lists:append(Elements, [Data]),
            listen(NewList2);
        stop ->
            io:format("Stopping.~n")
    end.

start() ->
    register(queue, spawn(queue, listen,[[]])).


Then from the shell I run:

queue ! {put, "ABC"}.
queue ! {put, "DEF"}.
queue ! {put, "GHI"}.
queue ! {get, self()}.
receive
{data, Data} -> io:format("Got ~s~n", [Data]);
empty -> io:format("Got empty~n");
AnyMessage -> io:format("Trap ~s~n", [AnyMessage]);
_ -> io:format("Got something else~n")
after 5000 -> io:format("timed out~n")
end.

And I get "Got ABC".  I do another get and the same receive as above and I
get:

** exception exit: {badarg,[{io,format,[<0.31.0>,"Trap
~s~n",[{data,"DEF"}]]},
                            {erl_eval,do_apply,5},
                            {shell,exprs,6},
                            {shell,eval_exprs,6},
                            {shell,eval_loop,3}]}
     in function  io:o_request/3


I don't understand why the {data, Data} pattern isn't receiving the
message.  Can someone help me understand this?


Thanks,

Kevin Hostelley

***** PLEASE NOTE ***** This E-Mail/telefax message and any
documents accompanying this transmission may contain privileged
and/or confidential information and is intended solely for the
addressee(s) named above. If you are not the intended
addressee/recipient, you are hereby notified that any use of,
disclosure, copying, distribution, or reliance on the contents of
this E-Mail/telefax information is strictly prohibited and may
result in legal action against you. Please reply to the sender
advising of the error in transmission and immediately
delete/destroy the message and any accompanying documents. Thank
you.*****  


More information about the erlang-questions mailing list