An output list is built by consing each of the elements that are part of the list and then advancing the recursion over the input, until the input is exhausted (in your case, when the number n
is one). By successively consing elements at the head of the list and ending the recursion with a null value, a new proper list is created and returned at the end of the procedure execution. Here's how:
(define (sequence n)
(cond [(= n 1) ; if n=1, it's the exit condition
(list n)] ; return a list with last element
[(even? n) ; if n is even
(cons n (sequence (/ n 2)))] ; cons n and advance the recursion
[(odd? n) ; if n is odd
(cons n (sequence (+ (* n 3) 1)))])) ; cons n and advance the recursion
The above will return a list with the Collatz sequence for the given number n
:
(sequence 6)
=> '(6 3 10 5 16 8 4 2 1)
As a side note: the procedures even?
and odd?
are standard in Scheme and you don't have to redefine them.