Erlang, Matching with list foreach -
i've been making chat application in erlang school project, i've run issue. i'm trying make program concurrent , in order start new thread each message channel sending. using lists:foreach, want make sure don't message person typed in channel.
request(state, {message, {userid,userpid}, token}) -> case catch lists:member({userid,userpid}, state#channel.users) of false -> {{error, user_not_joined}, state}; true -> spawn( fun() -> listofusers = state#channel.users, userpids = lists:map(fun ({_, v}) -> v end, listofusers), %spawn( fun() ->end) lists:foreach( fun(userpid) -> ok end, fun(pid) -> spawn( fun() -> genserver:request(pid, {message_from_server, state#channel.name, userid, token}) end) end, userpids) end), {ok, state} end;
what pretty want match userpid inside foreach. of warnings:
channel.erl:39: warning: variable 'userpid' unused channel.erl:39: warning: variable 'userpid' shadowed in 'fun'
line 3 fun(userpid) -> ok end,
cheers
the answer legoscia fine, i'd add list comprehension simpler use , simpler read lists:foreach
. note list comprehension able ignore values based on clauses. consider following example:
-module(filter). -export([do/0]). do() -> values = lists:seq(1,10), ignorethisvalue = 5, %% print values unequal ignorethisvalue [io:format("value: ~b~n", [value]) || value <- values, value =/= ignorethisvalue], ok.
run in shell:
1> make:all([load]). recompile: filter up_to_date 2> filter:do(). value: 1 value: 2 value: 3 value: 4 value: 6 value: 7 value: 8 value: 9 value: 10
a side note on code: why spawn thread per process? assume using behaviour gen_server
(correct me if wrong). if so, should consider using cast
function send message. not check result of genserver:request/2
, might viable option saves lot of processes.
Comments
Post a Comment