How to shuffle lists in Emacs

τэкnoкraτ

When I began to use Spacemacs I needed a way to shuffle the theme list. Normally I'd use a randomization function but as this is my first day in Spacemacs and I don't want to spend my time debugging intricacies of it, I decided to find a single function to shuffle a list. I googled for it but the top result was writing a custom function for it.

Then I searched the functions in the usual (holy) way. In Emacs it's C-h f and in Spacemacs it's SPC h d f. Searching by shuffle didn't return anything. I continued to search, as it's a basic functionality that should already be provided. Emacs Lisp docs for random numbers didn't return anything either.

Then searching through the code, I noticed there is a shuffle-vector function somewhere. (shuffle-vector [a b c d]) is supposed to return a shuffled vector, and it's possible to convert vectors to lists via append. However this function doesn't run in my Emacs 24.4 on Ubuntu. Then I noticed in Emacs sources that there is a function in a library called cookie1 that shows random quotations from files. This randomization uses a function called cookie-shuffle-vector as in (cookie-shuffle-vector [1 2 3 4 5 6]) returns a random permutation from this vector whenever called. In order to use this, however, one should call (require 'cookie1) before.

The remaining problem, converting Emacs vector to a list is easier: (append [a b c d] nil) converts a vector to a list of the same elements, hence the solution I was looking for in total is

(require 'cookie1)
(append (cookie-shuffle-vector [a b c d e f g]) nil)


Comments !