erlang 在 运行 快速排序后输出列表长度 - 第 2 部分
erlang output the list length after having it run a quicksort - Part 2
所以我的第一个问题是 ,这是有道理的。它能够在排序后输出列表长度,但最初我问的是将 io:format 函数用于 sort/0 的一种方法。但我的下一个跟进是如何将它与 sort/1 一起使用?我已经能够解决它来给出它,但是它在递归时给出它所以我得到多行并且不正确。我的问题是如何在完成快速排序后如何执行 io:format (另请注意,我也希望列表没有重复)所以我只得到长度的一行而不是多行我'我在下面?
这是我拥有的和正在得到的:
-module(list).
-export([sort/1]).
sort([]) -> [];
sort([First|Rest]) ->
io:format("~nThe length of the list is ~w~n", [length([First]++Rest)])),
sort([ X || X <- Rest, X < First]) ++
[First] ++
sort([ X || X <- Rest, X > First]).
并且输出:
56> list:sort([2,2,2,3,3,3,1,1,8,6]).
The length of the list is 10
The length of the list is 2
The length of the list is 5
The length of the list is 2
The length of the list is 1
[1,2,3,6,8]
所以没有重复的排序列表是正确的,但是我如何在其中安装 io:format 函数才能像这样显示?
56> list:sort([2,2,2,3,3,3,1,1,8,6]).
[1,2,3,6,8]
The length of the list is 5
除非我弄错了,否则您将无法按原样区分 io:format/2 inside
递归函数的用法。
您可以将打印与递归部分分开。
sort(L)->
Result = quicksort(L),
io:format("~nThe length of the list is ~w~n", [length(Result)]),
Result.
quicksort([]) -> [];
quicksort([First|Rest]) ->
quicksort([ X || X <- Rest, X < First]) ++
[First] ++
quicksort([ X || X <- Rest, X > First]).
所以我的第一个问题是
这是我拥有的和正在得到的:
-module(list).
-export([sort/1]).
sort([]) -> [];
sort([First|Rest]) ->
io:format("~nThe length of the list is ~w~n", [length([First]++Rest)])),
sort([ X || X <- Rest, X < First]) ++
[First] ++
sort([ X || X <- Rest, X > First]).
并且输出:
56> list:sort([2,2,2,3,3,3,1,1,8,6]).
The length of the list is 10
The length of the list is 2
The length of the list is 5
The length of the list is 2
The length of the list is 1
[1,2,3,6,8]
所以没有重复的排序列表是正确的,但是我如何在其中安装 io:format 函数才能像这样显示?
56> list:sort([2,2,2,3,3,3,1,1,8,6]).
[1,2,3,6,8]
The length of the list is 5
除非我弄错了,否则您将无法按原样区分 io:format/2 inside
递归函数的用法。
您可以将打印与递归部分分开。
sort(L)->
Result = quicksort(L),
io:format("~nThe length of the list is ~w~n", [length(Result)]),
Result.
quicksort([]) -> [];
quicksort([First|Rest]) ->
quicksort([ X || X <- Rest, X < First]) ++
[First] ++
quicksort([ X || X <- Rest, X > First]).