[racket] for/fold accum val at each step

From: Carl Eastlund (cce at ccs.neu.edu)
Date: Sat Aug 10 19:04:51 EDT 2013

The new value for the sum is not going to take effect until the next time
through the loop.  You're going to want to bind the new value for the sum
in a variable, and use that to produce the new average.  Also, is the
variable i guaranteed to count up from 1?  If so, your code is fine; if
not, you'd want a separate counter to compute the average with.

Here's an example:

(for/fold ([sum 0]
           [averages '()])
          ([i '(10 20 30 40)]
           [count (in-naturals 1)])
  (let* ([new-sum (+ sum i)]
         [new-average (/ new-sum count)])
    (values new-sum (cons new-average averages))))

... and it produces:

100
'(25 20 15 10)


Carl Eastlund


On Sat, Aug 10, 2013 at 6:56 PM, J G Cho <gcho at fundingmatters.com> wrote:

> I think I understand the following example from the documentation:
>
> (define (example)
>   (for/fold ([sum 0]
>              [averages null]) ;; 2 accums named sum and rev-roots are
> initialized
>             ([i '(1 2 3 4)]) ;; i will iterate over 1..4
>             (values
>              (+ sum i) ;; adding to sum
>              (cons (sqrt i) averages) ;; consing to rev-roots
>              )))
>
> (example) ->
> 10
> '(2 1.7320508075688772 1.4142135623730951 1)
>
>
> But I realize I don't really understand when I try the following:
>
> (define (example2)
>   (for/fold ([sum 0]
>              [averages null])
>             ([i '(1 2 3 4)])
>             (values
>              (+ sum i) ;; adding to sum
>              (cons (/ sum i) averages) ;; record running average but sum
> is not what I think it should be
>              )))
>
> (example2) ->
> 10
> '(1 1/2 1 1/2 0)
>
> Not reducing for readability, I was hoping for
> (10/4 6/3 3/2 1)
>
> How can I tweak the code?
>
> jGc
>
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130810/24b9cac6/attachment-0001.html>

Posted on the users mailing list.