erlang records trouble -
i'am struggling records in 1 of modules.
i defined on top of code record as:
-record(user, {pid, name, nick}).
in few words each user going represented process own pid , other fields.
later on in module doing following:
pid = userpid, getuser = fun(x) -> if x#user.pid =:= pid -> true; x#user.pid=/= pid -> false end end, user = lists:filter(getuser, users), io:format("user pid ~p~n",[user#user.pid]).
running code get:
** exception error: {badrecord,user}
but if do:
io:format("user ~p~n",[user]).
it prints
user [{user,<0.33.0>,name1,nick1}]
can point out missing?
thanks
emil's answer the lists:filter
function correct.
this how rewrite code, though:
-module(com). -record(user, {pid, name, nick}). -export([lookup/1]). lookup(pid) -> users = users(), filteredusers = [user || #user{pid = p} = user <- users, pid =:= p], lists:foreach(fun display/1, filteredusers). display(user) -> io:format("user name ~p~n",[user#user.name]). users() -> user1 = #user{pid = 1, name = "bob", nick = "bob"}, user2 = #user{pid = 2, name = "alice", nick = "alice"}, user3 = #user{pid = 1, name = "charlie", nick = "charlie"}, [user1, user2, user3].
i'm assuming can have multiple pids. if don't, can save foreach.
i believe using list comprehensions in case makes code more readable. also, following:
pid = userpid,
doesn't useful me...
Comments
Post a Comment