My Technical Notes

Wednesday, 16 March 2016

Elisp: Invoking a Lambda bound within a let statement

Incorrect use of Variable Bound to Lambda

Naively I thought this would work:


(let ((f (lambda (x) (* x x)))) (f 7))

but this gave the error message:


*** Eval error ***  Symbol's function definition is void: f

Correct use of Variable Bound to Lambda

The correct use of such a bound function, is to invoke it using `funcall`, which calls the function with the arguments specified after it:


(let ((f (lambda (x) (* x x)))) (funcall f 7))

which correctly gives `49`.

Use of `cl-flet`

There is a way of binding a function to a name by using `cl-flet`. We first import the `cl` module:

(require 'cl)

thereafter, we can define our lambda:


(cl-flet ((f (x) (* x x)))
  (f 7))

References

No comments: