# Talk:Guides/Lexical Closure

This is an archive of a discussion which originally took place on an earlier version of Lexical Closure:

## Other approaches

Can you list other ways to achieve lexical closure? -- Dan Bron

A simple one is this:

```foo =: +&
```

-- B Jonas

Nope, sorry:

```   foo =: +&
f =. 0 foo
f 0
0
f 3
3
f 2
2
f 5
5
f 0
0
```

-- Dan Bron

Oh, so you want a stateful function that stores the previous results and increments it in every step. Sorry. That's a bit more difficult in J it being a mostly side-effectless language. Let's see then.

```   acc_dat =: ''
acc_inc =: 4 :('t =. y. + x. { acc_dat'; 'acc_dat =: t x.} acc_dat'; 't')
acc =: 1 :'(<:# acc_dat =: acc_dat , u.) & acc_inc'
```

Then acc is the adverb that creates an accumulator function:

```   f =: 0 acc
g =: 0 acc
f 10
10
g 2
2
g 3
5
g 1
6
f 2
12
f 5
17
g 1
7
h =: 0 acc
f 2
19
h 1
1
g 2
9
```

There's no error checking and the counter for once allocated accumulator functions is never freed.

-- B Jonas

## dissent

Graham cites lexical scope as a feature of a "powerful" language. This appears to me like backwards reasoning. Graham likes Lisp; he thinks it's a powerful language. Lisp has lexical scope. Graham therefore concludes that all powerful languages must have lexical scope. Or, equivalently, a language must have lexical scope to be powerful.

I disagree with this conclusion. Lexical closure is incompatible with the functional programming model (a mathematical way of describing algorithms).

In the example section, notice how calling the same function with the same arguments produces a different result. A function whose output is not wholly determined by its input -- a function with "hidden inputs" -- is anathema to functional programming. (And yet, thinking about papers I've read, closures, "projections" and "monads" (in the Haskell/Scheme sense) are hot topics. So I must be wrong)

Contrast this with tacit definition in J, which does not even mention its arguments: mean =: +/ % #; this means tacit verbs are so dependent on their arguments that their indivual components' contexts are determined by their placement within the definition!

I maintain that functional programming is a powerful paradigm (in the same way mathematics is a powerful paradigm), and is at odds with lexical closure, and therefore lexical closure is not required of a powerful language. (Which is not the same as saying a language with lexical closure is not powerful, or that a language cannot achieve (greater) power through its addition.)

Regardless, because Graham is widely known and respected, his challenge has been and will be presented on the Forums, so we might as well answer it. Onward, then.

-- Dan Bron <<DateTime(2006-12-12T06:07:10Z)>>