Is there a way to write a function to create functions in Elisp?

I wanted to create a function that returns a composition from several other functions, such that

(funcall (compose 'f 'g) x) == (f (gx)) 

I feel like I was terribly unable to handle this. My best attempt:

 (defun compose (funcs) "composes several funcitons into one" (lambda (arg) (if funcs (funcall (car funcs) (funcall (compose (cdr funcs)) arg)) arg))) 

But for some reason, the following still returns 0:

 (funcall (compose '( (lambda (a) (* a 3)) (lambda (a) (+ a 2)) )) 0) 

Is there any way to fix this?

+4
source share
1 answer

Your code requires petal lambdas, which Emacs Lisp does not support by default. If you are using Emacs 24, set lexical-binding to t and your example will work as written.

If you are using older Emacs, you can create a lexically restricted lambda using the explicit lexical-let form:

 (require 'cl) (defun compose (funcs) "composes several funcitons into one" (lexical-let ((funcs funcs)) (lambda (arg) (if funcs (funcall (car funcs) (funcall (compose (cdr funcs)) arg)) arg)))) 
+6
source

Source: https://habr.com/ru/post/1443403/


All Articles