main_server_distributed.erl:66:警告:本條款所不能比擬的 因爲線61前款總是匹配
你已經基本上寫着:
get_chat_server(NonEmptyList, ChatServers) ->
{server, Pid, Reference,LoggedInUsers} = dict:fetch(Key,ChatServers),
LoggedInUsers < 100,
{server, Pid, Reference,LoggedInUsers};
get_chat_server(NonEmptyList, ChatServers) ->
get_chat_server(T, ChatServers).
因此,第一個子句總是與第二個子句匹配的任何東西匹配。更具體地講,在模式:
[Key|_]
Key
將匹配任何東西,_
將匹配任何東西。同樣,在模式:
[_|T]
_
將匹配任何東西,T
將匹配任何東西。
Riffing關@ dsmith的回答是:
-module(my).
-export([get_chat_server/3, get_chat_server_test/0]).
get_chat_server(_MaxLoggedIn, []=_Keys, _ChatServers) ->
none;
get_chat_server(MaxLoggedIn, [Key|Keys], ChatServers) ->
get_chat_server(MaxLoggedIn, Keys, ChatServers, dict:fetch(Key, ChatServers)).
get_chat_server(MaxLoggedIn, _, _, {_,_,_,LoggedInUsers}=ChatServer) when LoggedInUsers < MaxLoggedIn ->
ChatServer;
get_chat_server(MaxLoggedIn, [Key|Keys], ChatServers, _ChatServer) ->
get_chat_server(MaxLoggedIn, Keys, ChatServers, dict:fetch(Key, ChatServers)).
%---------
get_chat_server_test() ->
Keys = [a, c],
ChatServers = [
{a, {server, a, a_, 200}},
{b, {server, b, b_, 100}},
{c, {server, c, c_, 30}}
],
ChatServerDict = dict:from_list(ChatServers),
none = get_chat_server(10, [], ChatServerDict),
{server, c, c_, 30} = get_chat_server(50, Keys, ChatServerDict),
{server, c, c_, 30} = get_chat_server(150, Keys, ChatServerDict),
PossibleResults = sets:from_list([{server,a,a_, 200},{server,c,c_,30}]),
true = sets:is_element(
get_chat_server(250, Keys, ChatServerDict),
PossibleResults
),
all_tests_passed.
您還可以使用高階函數,即dict:fold(),讓所有符合您要求的ChatServers的列表:
max_fun(Max, Keys) ->
fun(Key, {_,_,_,LoggedInUsers}=Server, Acc) ->
case lists:member(Key, Keys) andalso LoggedInUsers<Max of
true -> [Server | Acc];
false -> Acc
end
end.
在外殼:
44> ChatServers = [
44> {a, {server, a, a_, 200}},
44> {b, {server, b, b_, 100}},
44> {c, {server, c, c_, 30}}
44> ].
[{a,{server,a,a_,200}},
{b,{server,b,b_,100}},
{c,{server,c,c_,30}}]
45> ChatServerDict = dict:from_list(ChatServers).
{dict,3,16,16,8,80,48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],
[[a|{server,a,a_,200}]],
[[b|{server,b,b_,100}]],
[[c|{server,c,c_,30}]],
[],[],[],[],[],[],[],[],[],[],[],[]}}}
46> Keys = [a,c].
[a,c]
47> MaxLoggedIn = 150.
150
50> F = my:max_fun(MaxLoggedIn, Keys).
#Fun<fl.0.128553666>
51> dict:fold(F, [], ChatServerDict).
[{server,c,c_,30}]