[erlang-questions] Help on dictionary search

Thomas Lindgren thomasl_erlang@REDACTED
Tue Nov 7 15:37:47 CET 2006



--- Bob Cowdery <Bob.Cowdery@REDACTED> wrote:

> I wonder if someone could help me with what I guess
> must seem a fairly elementary problem. 
> 
> I have a dictionary of the form [{class, [Pid, Pid,
> Pid ...]}, {class1[...]}, ...]. A given Pid can
> appear in one or more classes. Given a Pid I want to
> delete all instances of that Pid from the dictionary
> and if the class then has an empty list to remove
> the class. Generally I look up the dictionary by
> class and don't mind a linear search for the delete
> as its occational.
> 
> I think it's something like this, but I get lost on
> the details and don't know how to 'do something'
> with the head. Do I need to return a new dictionary.
>

How about this?

The following function deletes the PID from all the
class lists, but can leave {class, []} behind, which
you don't want:

delete_pid(PID, Classes) ->
   [ {Class, [ P || P <- PIDs, P =/= PID ]}
     || {Class, PIDs} <- Classes ].

There are a couple of ways to get rid of empty
classes. Use an extra pass:

delete_empty_classes(Classes) ->
   [ {Class, PIDS} 
     || {Class, PIDs} <- Classes, PIDs =/= [] ].

then run

delete_pid1(PID, Classes) ->
  delete_empty_classes(delete_pid(PID, Classes))

or rewrite delete_pid/2 to directly discard empty
classes:

delete_pid2(PID, [{Class, PIDs}|Classes]) ->
   case [ P || P <- PIDs, P =/= PID ] of
      [] -> delete_pid2(PID, Classes);
      Ps -> [{Class, Ps}|delete_pid2(PID, Classes)]
   end;
delete_pid2(PID, []) -> [].

That can also be written as a fold:

delete_pid3(PID, Classes) ->
   lists:foldr(
      fun({Class, PIDs}, Acc) ->
         case [ P || P <- PIDs, P =/= PID ] of
            [] -> Acc;
            Ps -> [{Class,Ps}|Acc]
         end
      end,
      [],
      Classes).

Warning: not extensively tested :-)

Best,
Thomas


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 



More information about the erlang-questions mailing list