[plt-scheme] Re: Some fine distinctions

From: wooks (wookiz at hotmail.com)
Date: Wed May 13 07:24:20 EDT 2009

>
> A function that uses an accumulator doesn't have to be in tail-
> recursive shape.
>
> An accumulator is an 'extra' parameter that keeps track of some  
> information between the "original" argument and the "current" one.  
> This is easier to explain with a small fragment:
>
>   ;; f : S -> T
>   (define (f s0)
>     ;; f-accu: S AccuType -> T
>     ;; accumulator: a keeps track of all ... between s0 and s
>     (define (f-accu s a)
>       ... (f-accu (selector s) (combine (other-selector s) a)) ... )
>     (f-accu s0 NULL_A))
>
> If S is a list type, then s0 is the head of the list and s is  
> somewhere in the middle.
>
> NULL_A is usually some "identity" for combine, because in the  
> beginning s == s0.
>
> -- Matthias

Didn't fully absorb that. So

sumlists :: listoflists -> number
(define sumlists
   (lambda (a-list)
      (let sumlists ([a-list a-list] [accum 0])
        (cond
         [(empty? a-list) 0]
         [(list? (first a-list)) (sumlists (rest a-list)
                                  (+ accum (sumlists (first a-list)))]
         [else (sumlists (rest a-list) (+ accum (first a-list)))]))))

This is accumulative and I used to think ergo tail recursive.
If I am right and it is not (because of the evaluation of the list?
case)...is there any way to write this sort of function tail
recursively. It looks to me not... at least not in this style of
programming.





Posted on the users mailing list.