Version 15 of Accumulator Generator

Updated 2009-12-27 20:17:13 by pmarin

There was an entry about this Topic (http://wiki.tcl.tk/3520 )


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; set n [expr {$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.

I'm not sure if garbage collection is obligatory to solve this problem.

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


WHD: How about this?

proc mkag {name n} {
    set ::${name} $n

    proc ::${name} {i} [list incr ::${name} \$i]
}

pmarin: Sorry, I don't understand your code, Can you make a similar test like the above? Note that the accumulator must work with integer and floats.