Visualize arbitrary tree in Racket using tree-layout

后端 未结 2 1809
轮回少年
轮回少年 2020-12-21 11:03

How to visualise arbitrary tree?

for example: (define T1 \'(and (or x1 x2)(or x3 x4 x5)))

or one generated with:

(define fun         


        
相关标签:
2条回答
  • 2020-12-21 11:13

    I think improvements can be made to assefamaru's answer -

    • Separate list traversal from individual node rendering
    • Simplify case analysis of input
      1. If the input is null (base case), return empty tree, #f
      2. Otherwise (inductive) the input is not null. If the input is a list, Create a tree-layout of op and recursively apply draw to args
      3. Otherwise (inductive) the input is not null and the input is not a list. Create a tree-layout of atom a

    Numbered lines above correspond to comments below -

    (define (my-node a)
      (cc-superimpose
       (disk 30 #:color "white")
       (text (symbol->string a))))
    
    (define (draw atom->pict a)
      (cond ((null? a) #f)                                 ;; 1
            ((list? a) (match a                            ;; 2
                         ((cons op args)
                          (apply tree-layout
                                 #:pict (atom->pict op)
                                 (map (curry draw atom->pict) args)))
                         (_ #f)))
            (else (tree-layout #:pict (atom->pict a)))))   ;; 3
    
    (define my-tree
      '(or (if A1 (and A1 (not (if D1 (and A0 A0) (or A0 A0)))) (or A0 A0)) D0))
    
    (naive-layered (draw my-node my-tree))
    

    0 讨论(0)
  • 2020-12-21 11:25

    You can do something like this to visualize arbitrarily sized trees:

    (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))))
    

    For example, using the lists you provided:

    (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))
    

    0 讨论(0)
提交回复
热议问题