Вопрос

(define key
  (lambda (w)
    (reverse w)
    (if (null? w)
     0
    (let ((k 33))
         (+ (* (ctv(car w)) k) (key (cdr w)))
))))

outputs the same thing as this:

(define key
  (lambda (w)
    (if (null? w)
     0
    (let ((k 33))
         (+ (* (ctv(car w)) k) (key (cdr w)))
))))

Why isn't my word reversed and then computed?

Input: (key '(x y z))

Output: 2475 (for both methods)

I don't understand why this happens. Someone please help me see why this is occurring.

Это было полезно?

Решение

As has been pointed, the reverse procedure returns a new list, it doesn't modify in-place the list that was passed as a parameter (this happens with all the procedures that modify lists, be careful with it). That's the reason why the line (reverse w) in your code doesn't have any effect: surely it returns a new reversed list, but you ignored the value that was returned!

For using the reversed list, you have to store or pass it along somewhere, a good idea would be to save it in a local variable defined inside a let form and refer to the variable from that point on. This is what @michaelb958 is suggesting:

(define key
  (lambda (w)
    (let ((w (reverse w)))
      (if (null? w)
          0
          (let ((k 33))
            (+ (* (ctv (car w)) k) (key (cdr w))))))))

However, be warned that the above will reverse the w list each time the recursion is called as it traverses the list, I don't think that's what you intend! if you need to reverse the list only once, call reverse before calling key, and don't ever call reverse inside key:

(key (reverse '(x y z)))

Другие советы

reverse just returns the reversed list, rather than reversing it in place. You'll need to

(let ((w (reverse w)))
  ...)

to get the effect you want.

Since, as others have noted, reverse does not reverse in place, your code should be modified as:

(define key
  (lambda (w)
    (set! w (reverse w))                ; CHANGE IS HERE
    (if (null? w)
         0
         (let ((k 33))
           (+ (* (ctv (car w)) k)
              (key (cdr w)))))))

Note, you are recursively calling key and thus you will be reversing back and forth, again and again.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top