Kryptos RSS

Archive

Apr
12th
Sun
permalink

Lambdas

From a recent post by andrej,

doesnt work

»> fs=[(lambda n:i+n) for i in range(10)]
»> fs[0](4)
13
»> fs[2](4)
13

works

»> fs=[(lambda i:lambda n:n+i)(j) for j in range(10)]
»> fs[3](4)
7
»> fs=[(lambda n,i=i:i+n) for i in range(10)]
»> fs[2](4)
6

Haskell

Prelude> let fs=[(\n -> i+n)|i <- [0..9]]
Prelude> [f(4) | f <- fs]
[4,5,6,7,8,9,10,11,12,13]

In Python, names are introduced by name binding operations. each occurence of a name in the prgm text refers to the binding of the name in the inner most function block containing the use

The problem is: Is there a better way to establish local bindings

i.e

Establish a binding i; For each integer in range do: SET i to the integer and evaluate the body of iteration construct

or

Foreach integer in range:establish a new binding from i to the integer and evaluate the body of the iteration construct