2016-06-30 52 views
-3

我試圖做的是閱讀{Jid, Text}功能,並檢查它是否已在列表返回true否則,如果是沒有這個功能應該把它添加到列表中,然後返回false二郎:檢查重複的元素

我」什麼在做的是:

new_seen() -> [{"[email protected]", "hello"}]. 

check({Jid, Text}) -> 
    Term = {Jid, Text}, 
    case lists:member(Term, new_seen()) of 
     true -> true; 
     false -> 
      %% here I want to add {Jid, Text} to new_seen() list. 
      false 
    end. 

簡單的例子:

check({"[email protected]", "hi"}). 
%% here should appened {"[email protected]", "hi"} to the list and return false. 


%% if I run function again : 
check({"[email protected]", "hi"}). 

%% here should return True cuz {"[email protected]", "hi"} in the list. 

我想用它來與ejabberd檢查DUPL插入消息。

+1

您的需求是?您需要在該列表中保存哪些數據?它是一個大型數據庫嗎?您可能需要檢查[Erlang ETS](http://erlang.org/doc/man/ets.html)或[Process Dictionary](http://erlang.org/doc/reference_manual/processes.html#id87983 ) –

+0

@ A.Sarid是的,這是一個很大的數據庫。是的,但我不應該使用ets或進程字典cuz有太多的數據。我也在這裏問: http://stackoverflow.com/questions/35958767/erlang-check-duplicate-inserted-elements 有沒有辦法做到這一點? –

+0

似乎你在你之前的問題中得到了你的答案。那麼,爲什麼不爲你的數據庫使用ETS呢?它應該完全適合大數據庫。 –

回答

1

你是否還檢查過不同的數據庫,如mnesia(Kev/Value Storage)?也許他們可以 看起來像一個map可以幫助你。您可以訪問特定鍵的值。你也應該檢查learnyousomeerlang

如果你需要一個列表,只需追加元素即可。與您的代碼:

check({Jid, Text}) -> 
    Term = {Jid, Text}, 
    case lists:member(Term, new_seen()) of 
     true -> true; 
     false -> 
      %% here I want to add {Jid, Text} to new_seen() list. 
      NewList = [Term|new_seen()] 
    end, 
NewList. 

你必須返回新的列表,並將其保存在其他地方,因爲你不能更新你的new_seen()函數列表。 如果您確實需要返回true,請將其放在最後一行:{true, NewList},它返回包含true和新列表的元組。

+0

是的,但我想如果他需要一個數據庫,他應該添加這個列表作爲函數的另一個參數:'check({Jid,Text},Database)'。並使用'Database'而不是調用'new_seen()'。 –