使用树布局可视化 Racket 中的任意树

X10*_*10D 3 tree visualization racket pict

如何可视化任意树?

例如: (define T1 '(and (or x1 x2)(or x3 x4 x5)))

或者使用以下命令生成:

(define functions '(not if and or))
(define terminals '(A0 A1 A2 D0 D1))
(define functions&terminals (append terminals functions ))

(define (pick-one list)
  (list-ref list (random (length list))))

(define arities '((if . 3)(and . 2)(or . 2)(not . 1)))

(define (terminal? symbol)
  (find (lambda (x)(eq? x symbol)) terminals))

(define (function? symbol)
  (find (lambda (x)(eq? x symbol)) functions))

(define (arity non-terminal)
  (let ((arity (find (lambda (x)(eq? non-terminal (car x))) arities)))
    (if arity
        (cdr arity)
        0)))

(define (numbers n)
  (if (= n 0) 
      '()
      (cons n (numbers (- n 1)))))

(define (gen-tree) 
  (let ((node (pick-one functions&terminals))) 
    (if (terminal? node) 
        node 
        (cons node (map (lambda (x) (gen-tree)) (numbers (arity 
node)))))))

> (gen-tree)
'(or (if A1 (and A1 (not (if D1 (and A0 A0) (or A0 A0)))) (or A0 A0)) D0)
Run Code Online (Sandbox Code Playgroud)

球拍似乎有: https ://docs.racket-lang.org/pict/Tree_Layout.html

使用圆圈中的函数名称和参数来可视化函数树是否足够?

ass*_*aru 6

您可以执行以下操作来可视化任意大小的树:

(require pict
         pict/tree-layout)

(define (draw tree)
  (define (viz tree)
    (cond
      ((null? tree) #f)
      ((not (pair? tree))
       (tree-layout #:pict (cc-superimpose
                            (disk 30 #:color "white")
                            (text (symbol->string tree)))))
      ((not (pair? (car tree)))
       (apply tree-layout (map viz (cdr tree))
              #:pict (cc-superimpose
                      (disk 30 #:color "white")
                      (text (symbol->string (car tree))))))))
  (if (null? tree)
      #f
      (naive-layered (viz tree))))
Run Code Online (Sandbox Code Playgroud)

例如,使用您提供的列表:

(define t1 '(and (or x1 x2) (or x3 x4 x5)))
(define t2 '(or (if A1 (and A1 (not (if D1 (and A0 A0) (or A0 A0)))) (or A0 A0)) D0))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 上面只是一个屏幕截图,但是您可以通过以下操作转换生成的图片并将其保存在本地:``(define generated-pict (draw tree))`` then ``(send (pict->bitmap generated-pict)保存文件“example.png”'png)``。 (3认同)