如何将列表划分为随机长度的(子)列表?

How do I partition a list into (sub-)lists of random length?

输入,举例(4为最大长度):

(my-partition-randomly '(a b c d e f g h i j k l) 4)

输出:

'((a b c) (d) (e f g h) (i j k) (l))

Emacs Lisp 解释器中的代码应该运行。

我的 elisp-fu 很弱,但我能够编写以下函数:

(defun my-partition-randomly (list max-length) ""
       (let ((result '()))
         (while list
           (push (seq-take-while (lambda (x) x)
                                 (map 'list
                                      (lambda (x) (pop list))
                                      (number-sequence 1 (+ 1 (random max-length)))))
                 result))
         (reverse result)))

它提取输入列表的随机初始序列并将它们添加到结果中(当最后一个子序列想要比剩余列表长时,seq-take-while 不需要包含 nils) . push 向左添加元素,所以结果必须反转。