⬅ Back to Rob Mayoff's Site Index

Paul Graham's Accumulator Generator, in PostScript

In Revenge of the Nerds, Paul Graham defines the accumulator generator problem. Solving it requires using a programming language that has, or can simulate, closures and a polymorphic add function. He presents solutions in a number of languages, submitted by various people.

He's no longer accepting solutions, but I managed to solve it in PostScript anyway:

/make-adder {
    [ exch
        [ exch ]
            dup 3 1 roll
            0 get add
            dup 3 1 roll
            0 exch put
        } /exec cvx
    ] cvx
} def

You can test it out in Ghostscript. For example:

GS>/x 1 make-adder def
GS>5 x ==
GS>/y 3 make-adder def
GS>2.3 x ==
GS>.7 x ==
GS>10 y ==
blog comments powered by Disqus