Compare commits

..

1 Commits

Author SHA1 Message Date
milo 632456dca7 improve dot generation 2026-03-24 16:12:52 -04:00
1 changed files with 16 additions and 45 deletions

59
dot.rkt
View File

@ -1,7 +1,6 @@
#lang racket/base #lang racket/base
(provide (provide
dot-graph
dot-digraph dot-digraph
dot-vertex dot-vertex
dot-edge) dot-edge)
@ -12,35 +11,26 @@
;; ----------------------------------------------------------------------------- ;; -----------------------------------------------------------------------------
(define current-dot-edge-syntax (make-parameter "--")) (define (dot-digraph f)
(write-string "digraph {\n")
(define ((dot-graph* header edge-stx) func) (f)
(write header)
(write-string " {\n")
(parameterize ([current-dot-edge-syntax edge-stx])
(func))
(write-string "}\n")) (write-string "}\n"))
(define dot-graph (dot-graph* 'graph "--"))
(define dot-digraph (dot-graph* 'digraph "->"))
(define (write-attrs attrs)
(for/fold ([beg "["] [end ""] #:result (write-string end))
([attr (in-list attrs)] #:when (cdr attr))
(write-string beg)
(printf "~a=~s" (car attr) (cdr attr))
(values "," "]")))
(define (dot-vertex id #:label [label #f] #:shape [shape #f]) (define (dot-vertex id #:label [label #f] #:shape [shape #f])
(let* ([params '()]
[params (if shape (cons (cons 'shape shape) params) params)]
[params (if label (cons (cons 'label label) params) params)])
(write id) (write id)
(write-attrs `([label . ,label] (for/fold ([beg "["] [end ""] #:result (write-string end))
[shape . ,shape])) ([param (in-list params)])
(write-string ";\n")) (write-string beg)
(printf "~a=~s" (car param) (cdr param))
(values "," "]"))
(write-string ";\n")))
(define (dot-edge a b #:flip? [flip? #f]) (define (dot-edge a b #:flip? [flip? #f])
(printf "~a ~a ~a;\n" (printf "~a -> ~a;\n"
(if flip? b a) (if flip? b a)
(current-dot-edge-syntax)
(if flip? a b))) (if flip? a b)))
(module+ test (module+ test
@ -48,39 +38,20 @@
(check-equal? (check-equal?
(with-output-to-string (with-output-to-string
(λ () (λ ()
(dot-graph (dot-digraph
(λ () (λ ()
(dot-vertex 'a) (dot-vertex 'a)
(dot-vertex 'b #:label "B") (dot-vertex 'b #:label "B")
(dot-vertex 'c #:shape 'box) (dot-vertex 'c #:shape 'box)
(dot-vertex 'd #:label "D" #:shape 'box))))) (dot-vertex 'd #:label "D" #:shape 'box)))))
(string-append (string-append
"graph {\n" "digraph {\n"
"a;\n" "a;\n"
"b[label=\"B\"];\n" "b[label=\"B\"];\n"
"c[shape=box];\n" "c[shape=box];\n"
"d[label=\"D\",shape=box];\n" "d[label=\"D\",shape=box];\n"
"}\n")) "}\n"))
(check-equal?
(with-output-to-string
(λ ()
(dot-graph
(λ ()
(dot-vertex 'a)
(dot-vertex 'b)
(dot-vertex 'c)
(dot-edge 'a 'b)
(dot-edge 'b 'c)
(dot-edge 'a 'c #:flip? #t)))))
(string-append
"graph {\n"
"a;\nb;\nc;\n"
"a -- b;\n"
"b -- c;\n"
"c -- a;\n"
"}\n"))
(check-equal? (check-equal?
(with-output-to-string (with-output-to-string
(λ () (λ ()