1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2014 Eric Bavier <bavier@member.fsf.org>
5 ;;; This file is part of GNU Guix.
7 ;;; GNU Guix is free software; you can redistribute it and/or modify it
8 ;;; under the terms of the GNU General Public License as published by
9 ;;; the Free Software Foundation; either version 3 of the License, or (at
10 ;;; your option) any later version.
12 ;;; GNU Guix is distributed in the hope that it will be useful, but
13 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;;; GNU General Public License for more details.
17 ;;; You should have received a copy of the GNU General Public License
18 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
20 (define-module (guix combinators)
21 #:use-module (ice-9 match)
22 #:use-module (ice-9 vlist)
30 ;;; This module provides useful combinators that complement SRFI-1 and
37 ((proc seed1 seed2 lst)
38 "Like `fold', but with a single list and two seeds."
39 (let loop ((result1 seed1)
43 (values result1 result2)
45 (lambda () (proc (car lst) result1 result2))
46 (lambda (result1 result2)
47 (loop result1 result2 (cdr lst)))))))
48 ((proc seed1 seed2 lst1 lst2)
49 "Like `fold', but with a two lists and two seeds."
50 (let loop ((result1 seed1)
54 (if (or (null? lst1) (null? lst2))
55 (values result1 result2)
57 (lambda () (proc (car lst1) (car lst2) result1 result2))
58 (lambda (result1 result2)
59 (fold2 proc result1 result2 (cdr lst1) (cdr lst2)))))))))
61 (define (fold-tree proc init children roots)
62 "Call (PROC NODE RESULT) for each node in the tree that is reachable from
63 ROOTS, using INIT as the initial value of RESULT. The order in which nodes
64 are traversed is not specified, however, each node is visited only once, based
65 on an eq? check. Children of a node to be visited are generated by
66 calling (CHILDREN NODE), the result of which should be a list of nodes that
67 are connected to NODE in the tree, or '() or #f if NODE is a leaf node."
68 (let loop ((result init)
74 (if (not (vhash-assq head seen))
75 (loop (proc head result)
76 (vhash-consq head #t seen)
77 (match (children head)
79 (children (append tail children))))
80 (loop result seen tail))))))
82 (define (fold-tree-leaves proc init children roots)
83 "Like fold-tree, but call (PROC NODE RESULT) only for leaf nodes."
86 (match (children node)
87 ((or () #f) (proc node result))
91 (define-syntax compile-time-value ;not quite at home
93 "Evaluate the given expression at compile time. The expression must
94 evaluate to a simple datum."
96 (let-syntax ((v (lambda (s)
99 (_ #`'#,(datum->syntax s val)))))))
102 ;;; combinators.scm ends here