2 回答

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
Erlang中刪除列表元素在標(biāo)準(zhǔn)模塊lists中可以找到delete/2函數(shù),
比如調(diào)用lists:delete(2, [1,2,3,4,5])后將返回新的列表[1,3,4,5]
筆者在翻閱lists模塊源碼中發(fā)現(xiàn),一些函數(shù)實(shí)現(xiàn)成BIF,比如reverse就是一個(gè)BIF,在注釋中發(fā)現(xiàn)
%% reverse(L) reverse all elements in the list L. Is now a BIF!
由此確定reverse是一個(gè)BIF。
但對(duì)delete函數(shù)的實(shí)現(xiàn)沒找到類似的注釋,懷疑其不是一個(gè)BIF,其實(shí)現(xiàn)存在性能問題,其實(shí)現(xiàn)代碼如下:
delete(Item, [Item|Rest]) -> Rest;
delete(Item, [H|Rest]) ->
[H|delete(Item, Rest)];
delete(_, []) -> [].
這個(gè)實(shí)現(xiàn)沒使用尾遞歸,對(duì)大表的操作將會(huì)導(dǎo)致堆棧上的內(nèi)存消耗嚴(yán)重。
測(cè)試程序如下:
test1() ->
{ok,Bin} = file:read_file("file1.txt"),
L = binary_to_list(Bin),
R = lists:delete($a,L),
io:format("~p~n",[length(R)]).
- 2 回答
- 0 關(guān)注
- 796 瀏覽
添加回答
舉報(bào)