SnakeDoc
SnakeDoc

Reputation: 14441

Returning list of lists

I'm having a tough time figuring out why my function buildList-aux does not return the correct contents of the list Z.

When I run debug mode, and pause on the if statement above return Z, I can see that the value in racket is correct and as expected, however the actual contents that gets returned and printed have some sort of error (overflow? or something) and prints (shared ((-1- (list 'abc))) (list -1- -1-)).

I'm running DrRacket 6.11, Advanced Student language.

(define buildList-aux
  (lambda (E Z count)
    (if (<= count 0)
        Z
        (if (not (list? E))
            (buildList-aux E (append (list E) Z) (- count 1))
            (buildList-aux E (cons E Z) (- count 1))))))

(define buildList
  (lambda (N E)
    (buildList-aux E '() N)))

(buildList 5 '())
(buildList 3 'A)
(buildList 2 '(abc))
(buildList 3 '(A))

Expected Output:

(list '() '() '() '() '())
(list 'A 'A 'A)
(list (list 'abc) (list 'abc))
(list (list 'A) (list 'A) (list 'A))

Actual Output:

(list '() '() '() '() '())
(list 'A 'A 'A)
(shared ((-1- (list 'abc))) (list -1- -1-))
(shared ((-1- (list 'A))) (list -1- -1- -1-))

Upvotes: 1

Views: 296

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236140

Your code is correct, it's just the way a list gets displayed in "Advanced Student". To see the correct output, do as @JohnClements suggests and go to "Language Details", and uncheck "Show Sharing in Values" box. Alternatively, switch to "Detect language from source" and specify #lang racket at the top of the file. Either way, the output will be as expected:

'(() () () () ())
'(A A A)
'((abc) (abc))
'((A) (A) (A))

But let's take a look at that weird output:

(shared ((-1- (list 'abc))) (list -1- -1-))

The above is stating that the result is:

(list -1- -1-)

Think of the -1- as a "variable" representing shared data, with a value of (list 'abc). If we substitute the "variable" with its value we get the more familiar:

(list (list 'abc) (list 'abc))

Upvotes: 2

Related Questions