Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of foldr, foldl in Emacs Lisp?

Tags:

emacs

lisp

elisp

What's the equivalent of foldr, foldl in Emacs Lisp?

like image 609
Thomas Avatar asked Nov 22 '10 11:11

Thomas


People also ask

What is the difference between Foldr and Foldl?

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.

Is Emacs a Lisp interpreter?

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.

Is Emacs Lisp the same as Lisp?

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.

Is Emacs functional Lisp?

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.


2 Answers

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))) 
like image 78
Gareth Rees Avatar answered Sep 24 '22 13:09

Gareth Rees


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) 
like image 20
Stefan Avatar answered Sep 21 '22 13:09

Stefan