One thing I find myself missing in emacs lisp is, surprisingly, a particular bit of list manipulation. I miss Python's concise list slicing.
>>> mylist = ["foo", "bar", "baz", "qux", "frobnitz"] >>> mylist[1:4] ['bar', 'baz', 'qux']
I see the functions butlast
and nthcdr
in the emacs documentation, which would give the same results from code like this:
(setq mylist '("foo" "bar" "baz" "qux" "frobnitz")) (butlast (nthcdr 1 mylist) 1) ;; ("bar" "baz" "qux")
Is there a more concise way of getting a list slice than combining butlast
and nthcdr
?
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.
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.
Sure there is:
(require 'cl-lib) (setq mylist '("foo" "bar" "baz" "qux" "frobnitz")) (cl-subseq mylist 1 4) ;; ("bar" "baz" "qux")
In modern Emacs, please note cl
is deprecated see In Emacs, what does this error mean? "Warning: cl package required at runtime"
Common Lisp library is great, but if your codebase becomes large and you want to write concise code in functional style, I endorse dash.el
library, which provides enormous amount of functions for list and tree manipulations. There is a function -slice
that behaves just like Python's slicing:
(-slice (number-sequence 1 10) 1 7 2) ; (2 4 6)
Arguments are in order: list, start, (optional) stop, (optional) step.
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