0

In an anonymous function such as

(lambda () x)

how can I replace the symbol x with its value in the current scope?

The only thing I can think of is

(eval `(lambda () ,x))

but I wonder if there's another way.

Drew
  • 29,895
  • 7
  • 74
  • 104
Ernest A
  • 7,526
  • 8
  • 34
  • 40

2 Answers2

1

Remove the eval. Just `(lambda () ,x).

That returns the list (lambda () VAL-X), where VAL-X is the value of variable x. And a lambda list is interpreted by Emacs as a function.

Ernest A
  • 7,526
  • 8
  • 34
  • 40
Drew
  • 29,895
  • 7
  • 74
  • 104
  • This will happily burp if `x` has a value such as `(1 2)`. – Stefan Dec 27 '16 at 21:40
  • 1
    @Stefan: I tried to stay as close to the OP as possible. And this returns `(lambda () (1 2))` - no burp. If you mean that *that* function burps when invoked, that's a different problem (and it applies to the OP too). If `x` is likely to be something that cannot be evaluated without error then `',x` is usually appropriate. – Drew Dec 27 '16 at 22:35
1

The better solution is to add

;; -*- lexical-binding:t -*-

at the beginning of your file. Once you've done that, writing (lambda () x) is all it takes, since Emacs will then take care of replacing that x with the value from the scope surrounding that lambda (i.e. will create a proper closure).

Stefan
  • 27,908
  • 4
  • 53
  • 82
  • The problem is it's not always possible to do that. For instance, imagine you're extending a library that doesn't use lexical binding. – Ernest A Dec 30 '16 at 08:50
  • It's always possible, and usually easy, to convert a file to `lexical-binding`. – Stefan Dec 30 '16 at 14:19