使用树布局可视化 Racket 中的任意树 [英] Visualize arbitrary tree in Racket using tree-layout

查看:38
本文介绍了使用树布局可视化 Racket 中的任意树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何可视化任意树?

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

或一个生成:

(定义函数'(不是if and or))(定义端子'(A0 A1 A2 D0 D1))(定义功能和终端(附加终端功能))(定义(选择一个列表)(list-ref list (random (length list))))(定义 arities '((if . 3)(and . 2)(or . 2)(not . 1)))(定义(终端?符号)(找到(lambda(x)(eq?x符号))终端))(定义(功能?符号)(查找(lambda(x)(eq?x 符号))函数))(定义(arity 非终端)(让 ((arity (find (lambda (x)(eq? non-terminal (car x))) arities)))(如果数量(cdr arity)0)))(定义(数字 n)(如果(= n 0)'()(cons n (numbers (- n 1))))))(定义(生成树)(让((节点(选择一个功能和终端)))(如果(终端?节点)节点(cons 节点 (map (lambda (x) (gen-tree)) (numbers (arity)节点)))))))>(基因树)'(或(如果A1(和A1(不是(如果D1(和A0 A0)(或A0 A0))))(或A0 A0))D0)

Racket 似乎有:

How to visualise arbitrary tree?

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

or one generated with:

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

Racket seems to have: https://docs.racket-lang.org/pict/Tree_Layout.html

is it enough to visualise trees of functions with the name of the function and params in the circle?

解决方案

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

这篇关于使用树布局可视化 Racket 中的任意树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆