Search code examples
erlangrecords

erlang records trouble


I'am struggling with records in one of my modules.

I defined on top of my code a record as:

-record(user,  {pid,
                name,
                nick}).

in few words each user is going to be represented as process with its own pid and other fields.

Later on in the module I am doing the 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 is ~p~n",[User#user.pid]).

Running this code I get:

** exception error: {badrecord,user}

But if I do:

io:format("User ~p~n",[User]).       

It prints

User [{user,<0.33.0>,name1,nick1}]

Can anyone point out what i am missing?

Thanks


Solution

  • Emil's answer about the lists:filter function is correct.

    This is how I would rewrite your 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  is ~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 you can have multiple pids. If you don't, you can save yourself the foreach.

    I believe that using list comprehensions in this case makes the code much more readable. Also, the following:

    Pid = UserPid,

    doesn't look very useful to me...