Reputation: 849
I am trying to perform the following action - i have a function that recieves a list and a number, for each occurrance of this number it should duplicate it in the output list, here is what i have so far:
(define (extendList lst num)
(define data (car lst))
(define nextData (cdr lst))
(cond ((and (number? data)(= data num)) ( list num num (extendList nextData num)))
(list? data) (list (extendList data num) (extendList nextData num))
(else ( list data (extendList (cdr lst) num) ))))
The thing is that it just doesnt call to this function again in recursion - all it does is adding the next element to the output, for example here is my input and my expected output:
(extendList '(6 x y 6) 6) ; output should be: (6 6 x y 6 6)
(extendList '(6 x (y 6) 6) 6) ;output should be: (6 6 x (y 6 6) 6 6)
but for both of the inputs it just returns the following:
'(6 6 x)
What am i doing wrong here? thanks in advance!
Upvotes: 0
Views: 154
Reputation: 6502
There are several problems:
You use cond
incorrectly. There's supposed to be a parenthesis around (list? data) (list (extendList data num) (extendList nextData num))
I suggest to use bracket around each branch (bracket and parenthesis are interchangeable), so that it's easier to read:
(define (extendList lst num)
(define data (car lst))
(define nextData (cdr lst))
(cond
[(and (number? data)(= data num)) (list num num (extendList nextData num))]
[(list? data) (list (extendList data num) (extendList nextData num))]
[else (list data (extendList (cdr lst) num))]))
You write a recursive function without a base case! What will happen if I call (extendList '() 6)
?
(list num num (extendList nextData num))
will create a list with three elements. I don't think this is what you actually want. You might want to use list*
or cons
instead. The same problem happens with other branches as well.
Upvotes: 2