2
votes

Im really having problems understanding how I can create variable that would act as an accumulator in racket. This is definitely a really stupid question....but racket's documentation is pretty difficult for me to read.

I know I will use some kind of define statement or let statement.

I want to be able to pass a number to a variable or function and it adds the current value with the new value keeps the sum...How would I do this....?? Thank you..

(define (accumulator newvalue) "current=current+newvalue" 

something like this..

3

3 Answers

4
votes

An accumulator is generally just a function parameter. There are a few chapters in How to Design Programs (online, starting here) that cover accumulators. Have you read them?

For example, the reverse function is implemented using an accumulator that remembers the prefix of the list, reversed:

;; reverse : list -> list
(define (reverse elems0)
  ;; reverse/accum : list list -> list
  (define (reverse/accum elems reversed-prefix)
    (cond [(null? elems)
           reversed-prefix]
          [else
           (reverse/accum (cdr elems)
                          (cons (car elems) reversed-prefix))]))
  (reverse/accum elems null))

Note that the scope of the accumulator reversed-prefix is limited to the function. It is updated by calling the function with a new value for that parameter. Different calls to reverse have different accumulators, and reverse remembers nothing from one call to the next.

Perhaps you mean state variable instead. In that case, you define it (or bind it with let or lambda) at the appropriate scope and update it using set!. Here's a global state variable:

;; total : number
(define total 0)

;; add-to-total! : number -> number
(define (add-to-total! n)
  (set! total (+ total n))
  total)

(add-to-total! 5) ;; => 5
(add-to-total! 31) ;; => 36

Here's a variation that creates local state variables, so you can have multiple counters:

;; make-counter : -> number -> number
(define (make-counter)
  (let ([total 0])
    (lambda (n)
      (set! total (+ total n))
      total)))

(define counterA (make-counter))
(define counterB (make-counter))

(counterA 5) ;; => 5
(counterB 10) ;; => 10
(counterA 15) ;; => 20
(counterB 20) ;; => 30

But don't call state variables accumulators; it will confuse people.

1
votes

Do you mean something like this?

(define (accumulator current newvalue)
  (let ((current (+ current newvalue)))
    ...)
0
votes

You can close over the accumulator variable:

(define accumulate
  (let ((acc 0))
    (λ (new-val)
      (set! acc (+ acc new-val))
      acc)))

(accumulate 10) ;=> 10
(accumulate 4)  ;=> 14