It depends of ets table content, what is best in "absolute" time. For short sets using lists:member/2 can be fastest.<br>For big data where amount of tuples with same first element is low, using ets:match_object/2 should be fastest.<br>
But for worst case, where there is big amount of tuples with same first elemnt, best should be transform ets talbe from bag to set where each item will be transformed by function (Tuple) -> {Tuple}. And time will be O(N). (But with big constant factor.)<br>
<br>check_list(List, Table) -><br> Set = ets:new(set, [set, private]),<br> true = ets:foldl(fun(X, _) -> true = ets:insert(Set, {X}) end, true, Table),<br> try lists:foreach(fun(X) -> case ets:member(Set, {X}) of true -> ok; false-> throw(not_found) end end, List) of <br>
_ -> true<br> catch<br> throw:not_found -> false<br> after<br> ets:delete(Set)<br> end.<br><br><br><div class="gmail_quote">2008/6/20 Doug Edmunds <<a href="mailto:dougedmunds@gmail.com">dougedmunds@gmail.com</a>>:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">Scenario:<br>The goal is determine if any tuples in the List are not<br>in the Table (and if so, identify which are missing).<br>
<br>I wrote two functions, one which uses ets:match_object/2 and<br>the other which uses lists:member/2.<br>
<br>Function parameters: <br>
List is a list of tuples [{a,b}, {c,d,e}, {a,d}, ...].<br>
Table is an open ets table of type 'bag', which means<br>
there can be more than one item with the same key in <br>
the table. <br>
<br>Which of these methods is preferable, and why?<br><br>%% a quick display utility function<br>io(X) -> io:format("~p~n",[X]).<br><br>findlist1(List,Table) -><br> R1 = [E || E <- List, length(ets:match_object(Table, E)) == 0],<br>
io(R1), %% elements not found in table<br> io(length(R1)). %% if length(R1) == 0, all are in list <br><br>findlist2(List, Table) -><br> AsList = ets:tab2list(Table),<br> R1 = [E || E <- List, not lists:member(E,AsList)],<br>
io(R1), %% same as above<br> io(length(R1)). <br><br>length(R1) could be turned into true/false thus:<br><br>case length(R1) of<br><br> 0 -> true; % all in table<br> _Other -> false<br>end. <br>
<br>What are some other alternatives?<br><br>Also, I would appreciate suggestions on<br>how to short-circuit the evaluation <br>(stopping as soon as one element of the<br>list is not found in the table).<br><br>Thanks.<br>
<br>-dae<br>
<br>_______________________________________________<br>
erlang-questions mailing list<br>
<a href="mailto:erlang-questions@erlang.org">erlang-questions@erlang.org</a><br>
<a href="http://www.erlang.org/mailman/listinfo/erlang-questions" target="_blank">http://www.erlang.org/mailman/listinfo/erlang-questions</a><br></blockquote></div><br><br clear="all"><br>-- <br>--Hynek (Pichi) Vychodil