<div dir="ltr"><div>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.<br>
<br></div>Here's an example:<br><div><br>(for/fold ([sum 0]<br> [averages '()])<br> ([i '(10 20 30 40)]<br> [count (in-naturals 1)])<br> (let* ([new-sum (+ sum i)]<br> [new-average (/ new-sum count)])<br>
(values new-sum (cons new-average averages))))<br><br></div><div>... and it produces:<br></div><div><br>100<br>'(25 20 15 10)<br><br></div></div><div class="gmail_extra"><br clear="all"><div>Carl Eastlund</div>
<br><br><div class="gmail_quote">On Sat, Aug 10, 2013 at 6:56 PM, J G Cho <span dir="ltr"><<a href="mailto:gcho@fundingmatters.com" target="_blank">gcho@fundingmatters.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div dir="ltr">I think I understand the following example from the documentation:<div><br></div><div><div>(define (example)</div><div> (for/fold ([sum 0]</div><div> [averages null]) ;; 2 accums named sum and rev-roots are initialized</div>
<div> ([i '(1 2 3 4)]) ;; i will iterate over 1..4</div><div> (values </div><div> (+ sum i) ;; adding to sum</div><div> (cons (sqrt i) averages) ;; consing to rev-roots</div>
<div> )))</div><div><br></div><div>(example) -></div><div>10</div><div>'(2 1.7320508075688772 1.4142135623730951 1)</div></div><div><br></div><div><br></div><div>But I realize I don't really understand when I try the following:</div>
<div><br></div><div><div>(define (example2)</div><div> (for/fold ([sum 0]</div><div> [averages null])</div><div> ([i '(1 2 3 4)])</div><div> (values </div><div> (+ sum i) ;; adding to sum</div>
<div> (cons (/ sum i) averages) ;; record running average but sum is not what I think it should be</div><div> )))</div></div><div><br></div><div>(example2) -></div><div><div>10</div><div>'(1 1/2 1 1/2 0)</div>
</div><div><br></div><div>Not reducing for readability, I was hoping for</div><div>(10/4 6/3 3/2 1)</div><div><br></div><div>How can I tweak the code?</div><span class="HOEnZb"><font color="#888888"><div><br></div><div>jGc</div>
</font></span></div>
<br>____________________<br>
Racket Users list:<br>
<a href="http://lists.racket-lang.org/users" target="_blank">http://lists.racket-lang.org/users</a><br>
<br></blockquote></div><br></div>