gsamerica
gsamerica

Reputation: 153

Constructing a list of numbers in Scheme

I'm doing a programming assignment in Scheme where we have to develop a method of finding Happy Numbers. I've completed the meat (finding Happy numbers from a number n) but I'm having trouble constructing a list correctly.

Here is my code:

(sosd num) calculates num's Happy Number and (stop? num) determines if num is a recursive number from a predetermined list.

(define (sspd_series num)
  (if (stop? num)
      (make-list num)
      (append (make-list(sosd num)) (make-list(sspd_series (sosd num))))
      )
  )

(define (make-list num)
  (cons num '())
  )

However while I want a list that looks like (1 2 3 4 5), I get (1 (2 (3 (4 (5))))). I've tried cons instead of append and I get something different, but not what I'm looking for.

What am I doing wrong?

Upvotes: 0

Views: 946

Answers (2)

Sylwester
Sylwester

Reputation: 48745

The smart thing is to find a way to create your list in reverse order. Imagine you start with '() you make '(3) with (cons 3 '()) and you make '(2 3) with (cons 2 '(3)). As inspiration here is how to reverse a list:

(define (my-reverse lst)
  (let loop ((lst lst) (acc '()))
    (if (null? lst)
        acc
        (loop (cdr lst) (cons (car lst) acc)))))

Upvotes: 1

Óscar López
Óscar López

Reputation: 236034

Assuming that stop? and sosd are correctly implemented, you just have to build a proper list as output, use cons for that. This is how:

(define (sspd_series num)
  (if (stop? num)
      (list (sosd num))
      (cons (sosd num)
            (sspd_series (sosd num)))))

You can optimize the implementation by calculating sosd only once at the start of the procedure, and storing it in a variable. Left as an exercise for the reader.

Upvotes: 1

Related Questions