guix: utils: Add flatten and flat-map from haunt.

* guix/utils.scm (flatten, flat-map): Add procedures.

Change-Id: I1d7d49fd02115e3de09ed69bcf5f55a10423162e
This commit is contained in:
Herman Rimm 2024-09-19 21:44:27 +02:00 committed by Ryan Schanzenbacher
parent b25d63e198
commit d0767b5a23
Signed by: ryan77627
GPG key ID: 81B0E222A3E2308E

View file

@ -139,6 +139,9 @@ (define-module (guix utils)
with-environment-variables with-environment-variables
arguments-from-environment-variable arguments-from-environment-variable
flatten
flat-map
config-directory config-directory
cache-directory cache-directory
@ -1028,6 +1031,29 @@ (define (with-atomic-file-output file proc)
(false-if-exception (delete-file template)) (false-if-exception (delete-file template))
(close-port out))))) (close-port out)))))
;; TODO: bring over other utility procedures from (haunt utils).
(define* (flatten lst #:optional depth)
"Return a list that recursively concatenates the sub-lists of LST,
up to DEPTH levels deep. When DEPTH is #f, the entire tree is
flattened."
(if (and (number? depth) (zero? depth))
lst
(fold-right (match-lambda*
(((sub-list ...) memo)
(append (flatten sub-list (and depth (1- depth)))
memo))
((elem memo)
(cons elem memo)))
'()
lst)))
(define (flat-map proc . lsts)
"Apply PROC to each element of each list in LSTS and return a new
list in which nested lists are concatenated into the result.
For example, the list (1 2 (3)) would be flattened to (1 2 3)."
(flatten (apply map proc lsts) 1))
(define* (xdg-directory variable suffix #:key (ensure? #t)) (define* (xdg-directory variable suffix #:key (ensure? #t))
"Return the name of the XDG directory that matches VARIABLE and SUFFIX, "Return the name of the XDG directory that matches VARIABLE and SUFFIX,
after making sure that it exists if ENSURE? is true. VARIABLE is an after making sure that it exists if ENSURE? is true. VARIABLE is an