What's the equivalent of foldr, foldl in Emacs Lisp?
Difference Between foldl and foldr The difference is that foldl is tail-recursive, whereas foldr is not. With foldr and non-optimized patterns, proc is applied to the current value and the result of recursing on the rest of the list. That is, evaluation cannot complete until the entire list has been traversed.
Emacs Lisp is a dialect of the Lisp programming language used as a scripting language by Emacs (a text editor family most commonly associated with GNU Emacs and XEmacs). It is used for implementing most of the editing functionality built into Emacs, the remainder being written in C, as is the Lisp interpreter.
By default, Common Lisp is lexically scoped, that is, every variable is lexically scoped except for special variables. By default, Emacs Lisp files are dynamically scoped, that is, every variable is dynamically scoped.
Emacs Lisp supports multiple programming styles or paradigms, including functional and object-oriented. Emacs Lisp is not a purely functional programming language since side effects are common. Instead, Emacs Lisp is considered an early functional flavored language.
If you
(require 'cl)
then you can use the Common Lisp function reduce
. Pass the keyword argument :from-end t
for foldr
.
ELISP> (reduce #'list '(1 2 3 4)) (((1 2) 3) 4) ELISP> (reduce #'list '(1 2 3 4) :from-end t) (1 (2 (3 4)))
Since Emacs-24.3 we recommend the use of cl-lib
over cl
(which is planned for removal in some distant future), so it would be:
(require 'cl-lib) (cl-reduce #'+ '(1 2 3 4))
and since Emacs-25, you can also use the seq
package for that:
(require 'seq) (seq-reduce #'+ '(1 2 3 4) 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With