0

So my first question was answered and it makes sense. It was able to output a list length after a sort, but originally I was asking as a way to use io:format function for a sort/0. But my next follow up, is how to use it with the sort/1? I've been able to work it out to give it, but it's giving it while recursion so I'm getting multiple lines and incorrectly. My question is how do I do the io:format once it's done with quick sort (also note, I also want the list to have no repeats) so I get just the one line of the length instead of the multiple lines I'm getting below?

Here's what I have and am getting:

-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]).

And the output:

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]

So the sorted list with no duplicates is correct, but how do I fit the io:format function in there to show like this?

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
Community
  • 1
  • 1
chitown88
  • 27,527
  • 4
  • 30
  • 59

1 Answers1

3

Unless I am mistaken, you are not going to be able to discriminate the usage of io:format/2 inside the recursive function as it is.

You could separate the printing from the recursive part.

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]).
Asier Azkuenaga
  • 1,199
  • 6
  • 17
  • Ya my problem was I was not thinking of it as a function within the function. So this makes sense. Thanks for answering my rookie question. – chitown88 Apr 02 '17 at 11:50