Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a concise emacs lisp equivalent of Python's [n:m] list slices?

Tags:

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?

like image 754
Brighid McDonnell Avatar asked Nov 01 '12 19:11

Brighid McDonnell


People also ask

Is Emacs Lisp the same as Lisp?

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 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

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"

like image 60
Bozhidar Batsov Avatar answered Oct 09 '22 04:10

Bozhidar Batsov


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.

like image 39
Mirzhan Irkegulov Avatar answered Oct 09 '22 06:10

Mirzhan Irkegulov