开发者

Is it possible to write this without an accumulator?

开发者 https://www.devze.com 2023-04-05 00:44 出处:网络
I origin开发者_运维百科ally tried writing this without being tail recursive, as according to http://www.erlang.org/doc/efficiency_guide/myths.html the BEAM does it itself. It works, I\'m just wonderin

I origin开发者_运维百科ally tried writing this without being tail recursive, as according to http://www.erlang.org/doc/efficiency_guide/myths.html the BEAM does it itself. It works, I'm just wondering if my code is overly ugly/inefficient. The one at literate programs http://en.literateprograms.org/Selection_sort_%28Erlang%29 seems a little bit less concise than my version, yet I feel mine has too many params to be easily understood. I am unsure if I would feel this way if I was more experienced with recursion.

-module(selection).
-export([selection/1]).

selection([H|T]) -> lists:reverse(selection(T,H,[],[])).

selection([],Min,[H|T],Acc) -> selection(T,H,[],[Min|Acc]);
selection([],Min,[],Acc) -> [Min|Acc];
selection([H|T],Min,Rest,Acc) when H < Min -> selection(T,H,[Min|Rest],Acc);
selection([H|T],Min,Rest,Acc) -> selection(T,Min,[H|Rest],Acc).


Here is one version:

-module(selection).

-export([selection/1]).

selection([]) -> [];
selection([H|T]) -> 
  {Min, Rest} = remove_min(H, T, []),
  [Min | selection(Rest)].

remove_min(Min, [], Rest) -> {Min, Rest};
remove_min(SoFar, [H|T], Acc) when H < SoFar ->
  remove_min(H, T, [SoFar|Acc]);
remove_min(Min, [H|T], Acc) -> remove_min(Min, T, [H|Acc]).

Or getting maximum as YOUR ARGUMENT IS VALID pointed out with accumulator but without reverse:

selection([H|T]) -> selection(T,H,[],[]).

selection([],Max,[H|T],Acc) -> selection(T,H,[],[Max|Acc]);
selection([],Max,[],Acc) -> [Max|Acc];
selection([H|T],Max,Rest,Acc) when H > Max -> selection(T,H,[Max|Rest],Acc);
selection([H|T],Max,Rest,Acc) -> selection(T,Max,[H|Rest],Acc).

It seems both have almost same performance.

0

精彩评论

暂无评论...
验证码 换一张
取 消