views:

809

answers:

5

I'm trying to create a function on the fly that would return one constant value.

In JavaScript and other modern imperative languages I would use closures:

function id(a) {
    return function() {return a;};
}

but Emacs lisp doesn't support those.

I can create mix of identity function and partial function application but it's not supported either.

So how do I do that?

+3  A: 

Stupid idea: how about:

(defun foo (x)
  `(lambda () ,x))

(funcall (foo 10))  ;; => 10
Ken
This breaks down when you want to write something like: (lexical-let((a 0)) (cons (lambda () a) (lambda (new-a) (setf a new-a))))
jrockway
+11  A: 

Found another solution with lexical-let

(defun foo (n) 
    (lexical-let ((n n)) #'(lambda() n)))

(funcall (foo 10)) ;; => 10
vava
+4  A: 

I am not firm in Emacs Lisp, but as far as I know, a big difference from Common Lisp is that it uses dynamic scoping throughout. The Emacs Lisp Manual states that Emacs Lisp doesn't have closures.

I'll try to apply my theoretical knowledge of dynamic scoping.

If you have a function id which just returns the value of my-id:

(defun id ()
  my-id)

and you use it in some other function:

(defun some-other-place ()
  (id))

and somewhere on the way to the call of id you bind my-id through e.g. a let:

(defun even-elsewhere ()
  (let ((my-id 5))
    (some-other-place)))

this should give back 5.

I know that dynamic scoping is a strange beast when you are used to lexical scoping, but perhaps you can use this to implement your desired behaviour.

Svante
Wow, that's cool :)
vava
+5  A: 

Emacs lisp only has dynamic scoping. There's a lexical-let macro that approximates lexical scoping through a rather terrible hack.

Allen
Of course, the `rather terrible hack' is what goes on under the coversof other language implementations.
jrockway
A: 

arent closures due to dynamical binding, not due to dynamical scoping?

Bernd Schmitt