Skip to content

Commit

Permalink
Update srfi.234 to the latest reference impl
Browse files Browse the repository at this point in the history
  • Loading branch information
shirok committed Sep 19, 2024
1 parent 540859f commit b3f0289
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 9 deletions.
31 changes: 22 additions & 9 deletions lib/srfi/234.scm
Original file line number Diff line number Diff line change
@@ -1,28 +1,41 @@
;;; SPDX-FileCopyrightText: 2024 Shiro Kawai, John Cowan, Arne Babenhauserheide
;;; SPDX-License-Identifier: MIT

;;; Code adapted from gauche https://github.com/shirok/Gauche/blob/master/lib/util/toposort.scm :
;;;
;;; srfi-234.scm - topological sorting
;;;
;;; Written by Shiro Kawai ([email protected]) 2001
;;; Public Domain.. I guess lots of Scheme programmers have already
;;; written similar code.
;;;
;;; Arne Babenhauserheide 2023--2024
;;; Public Domain.

(define-module srfi.234
(export topological-sort
edgelist->graph
edgelist/inverted->graph
graph->edgelist
graph->edgelist/inverted
connected-components))
(export topological-sort topological-sort/details
edgelist->graph edgelist/inverted->graph
graph->edgelist graph->edgelist/inverted
connected-components)
)
(select-module srfi.234)


(define topological-sort
(case-lambda
((graph) (topological-sort-impl graph equal? #f))
((graph eq) (topological-sort-impl graph eq #f))
((graph eq nodes) (topological-sort-impl graph eq nodes))))

(define topological-sort/details
(case-lambda
((graph) (topological-sort-impl/details graph equal? #f))
((graph eq) (topological-sort-impl/details graph eq #f))
((graph eq nodes) (topological-sort-impl/details graph eq nodes))))

(define (topological-sort-impl graph eq nodes)
(let-values (((v0 v1 v2)
(topological-sort-impl/details graph eq nodes)))
v0))

(define (topological-sort-impl/details graph eq nodes)
(define table (map (lambda (n)
(cons (car n) 0))
graph))
Expand Down
30 changes: 30 additions & 0 deletions test/include/srfi-234-test.scm
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
;;; SPDX-FileCopyrightText: 2024 Shiro Kawai, John Cowan, Arne Babenhauserheide
;;; SPDX-License-Identifier: MIT

(cond-expand
(guile
(import (scheme base)
Expand All @@ -8,6 +11,7 @@
(import (scheme base)
(srfi 234)
(srfi 1)
(srfi 11) ;; let-values
(rename (except (chibi test) test-equal)
(test test-equal))))
(chicken
Expand All @@ -32,6 +36,32 @@
(c)
(d c))))

;; details: multiple values
(test-equal
'((a b d c) #f #f)
(let-values
(((v0 v1 v2)
(topological-sort/details '((a b c)
(b d)
(c)
(d c)))))
(list v0 v1 v2)))

;; cycle
(test-equal
#f
(topological-sort '((a b)
(b a))))

;; cycle error details
(test-equal
'(#f "graph has circular dependency" (a b))
(let-values
(((v0 v1 v2)
(topological-sort/details '((a b)
(b a)))))
(list v0 v1 v2)))

(test-equal
'("a" "b" "d" "c")
(topological-sort '(("a" "b" "c")
Expand Down

0 comments on commit b3f0289

Please sign in to comment.