erlang - is it possible to output the list length after having it run a quicksort?

自闭症网瘾萝莉.ら 提交于 2019-12-24 07:38:28

问题


I'm a newbie to Erlang. I've been running a quick sort on a random list of numbers (i've also had it only keep unique numbers so duplicates do not show up in the sorted list). It works fine in that the output is giving the sorted numbers with no duplicates, but I have been trying to have it output not only the list, but also the length list too which is where I'm running into errors.

The length(mod:func). will give the length of the list no problem in the erlang shell, but I can't get it to work to do it after the recursion of the quick sort. I've tried assigning variables and doing lists:append. I just don't know what I'm doing wrong.

Can anyone explain?

Sorry, I forgot to attach the code below. It's the basic quicksort.

-module(list).
-export([sort/0]).
-export([sort/1]).

sort() -> sort([3,3,3,4,1,2,3,2,6,5,9,11,3,10,5]).

sort([]) -> [];

sort([Pivot|Tail]) ->  

    sort([ X || X <- Tail, X < Pivot]) ++

    [Pivot] ++

    sort([ X || X <- Tail, X > Pivot]).

When I run it in the shell, the list is good. And if I run the length function, it gives 9 which is what I want.

55> c(list).    
{ok,list}
56> list:sort().
[1,2,3,4,5,6,9,10,11]
57> length(list:sort()).
9

But I'm trying to get it to just do list:sort() and then give both the list and the length of the list right after. I've tried a bunch of different things, and I've tried to look it up but can't seem to find how to combine the two in one module to work together. It just seems like the length BIF is pretty straight forward function and I'm just not using/going about it the right way. Does that make sense?

I would like it to say something like:

55> c(list).    
{ok,list}
56> list:sort().
[1,2,3,4,5,6,9,10,11]
The length of the list is 9

回答1:


You can print out the list length by using io:format/2. Just need to modify your sort/0 function to add in a line for it:

 sort() -> 
     Sorted = sort([3,3,3,4,1,2,3,2,6,5,9,11,3,10,5]),
     io:format("~p~nThe length of the list is ~w~n", [Sorted, length(Sorted)]).



回答2:


1> S = fun S([]) -> {[],0};                 
1> S([P|T]) ->                              
1> {Small,LSmall} = S([X || X <- T, X < P]),
1> {Big,LBig}= S([X || X <- T, X > P]),     
1> {Small ++ [P] ++ Big, LSmall+LBig+1}     
1> end.                                     
#Fun<erl_eval.30.52032458>
2> S([3,3,3,4,1,2,3,2,6,5,9,11,3,10,5]).
{[1,2,3,4,5,6,9,10,11],9}
3>


来源:https://stackoverflow.com/questions/43027957/erlang-is-it-possible-to-output-the-list-length-after-having-it-run-a-quicksor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!