Version 10 of Accumulator Generator

Updated 2009-12-27 18:40:50 by pmarin

The Accumulator Generator is a problem used by Paul Graham to compare the relative power of differents programming languages.

The Problem

We want to write a function that generates accumulators-- a function that takes a number n, and returns a function that takes another number i and returns n incremented by i.

(That's incremented by, not plus. An accumulator has to accumulate.)

The original essay: http://www.paulgraham.com/icad.html

The implementation in other languages: http://www.paulgraham.com/accgen.html

My implementation:

package require TclOO
namespace import oo::*

proc foo n {
        set obj [object new]        
        objdefine $obj method init {_n} {my variable n; set n $_n}
        objdefine $obj method acc i {my variable n; incr n $i}
        $obj init $n
        list ::apply [list i [subst -novariables {[set obj] acc $i}]]
}
proc destroy_acc acc {
        [lindex $acc 1 1 0] destroy
}

A test:

> set acc [foo 3]
> {*}$acc 1
4
> {*}$acc 10
14
> {*}$acc 0
14

> destroy_acc $acc
> {*}$acc 1
invalid command name "::oo::Obj

Comments

I'm not happy with my implementation, It works but It is still too vebose compared with other languages.

Feel free to insert here your own better/clever approach.