List 在Erlang中列出帮助
您好,我正在尝试编写一个函数,该函数返回一个只包含列表唯一元素的列表,例如[1,2,3,1,1,2,3,4,5,5,1]->[1,2,3,4,5] 唯一的问题是,除了我正在编写的这个函数,我不能使用任何其他函数(不允许) 因此: 独特([H | T])->有什么想法吗List 在Erlang中列出帮助,list,recursion,erlang,List,Recursion,Erlang,您好,我正在尝试编写一个函数,该函数返回一个只包含列表唯一元素的列表,例如[1,2,3,1,1,2,3,4,5,5,1]->[1,2,3,4,5] 唯一的问题是,除了我正在编写的这个函数,我不能使用任何其他函数(不允许) 因此: 独特([H | T])->有什么想法吗 (与递归有关)非常不言自明,一个执行唯一检查的find helper函数 check_unique(List) -> check_unique(List, []). check_unique([H|T], Acc)
(与递归有关)非常不言自明,一个执行唯一检查的find helper函数
check_unique(List) ->
check_unique(List, []).
check_unique([H|T], Acc) ->
case find(H, Acc) of
true ->
check_unique(T, Acc);
false ->
check_unique(T, Acc ++ [H])
end;
check_unique([], Acc) ->
Acc.
find(E, [E|_]) ->
true;
find(E, [_|T]) ->
find(E, T);
find(_E, []) ->
false.
不是最快的实现,但很简单
unique(L) -> unique(L, []).
unique([], UL) -> UL;
unique([H|T], UL) ->
case lists:member(H,UL) of
true ->
unique(T, UL);
false ->
unique(T, [H|UL])
end.
该函数以相反的方式生成列表。您可以调用列表:reverse()
没有库函数的短函数:
unique(L) -> unique (L,[]).
unique([],R) -> R;
unique([H|Q],R) ->
case [Y || Y <- Q, Y =:= H] of
[] -> unique(Q,[H|R]);
_ -> unique(Q,R)
end.
unique(L)->unique(L,[])。
唯一([],R)->R;
唯一([H | Q],R)->
格[Y|Y唯一(Q[H|R]);
_->唯一(Q,R)
结束。
我使用了=:=比较,因此1和1.0被认为是不同的。可能重复的
unique(L) -> unique (L,[]).
unique([],R) -> R;
unique([H|Q],R) ->
case [Y || Y <- Q, Y =:= H] of
[] -> unique(Q,[H|R]);
_ -> unique(Q,R)
end.