List 在方案中跨树节点应用函数
我在Dr.Racket中使用的是Simply Scheme 问题是编写树映射,类似于深度映射,但对于树,使用数据选择器和子选择器。这是深度地图:List 在方案中跨树节点应用函数,list,tree,scheme,List,Tree,Scheme,我在Dr.Racket中使用的是Simply Scheme 问题是编写树映射,类似于深度映射,但对于树,使用数据选择器和子选择器。这是深度地图: (define (deep-map f structure) (cond ((word? structure) (f structure)) ((null? structure) '()) (else (cons (deep–map f (car structure)) (de
(define (deep-map f structure)
(cond ((word? structure) (f structure))
((null? structure) '())
(else (cons (deep–map f (car structure))
(deep–map f (cdr structure))))))
这是我迄今为止对树形图的尝试:
(define (tree-map f structure)
(cond ((leaf? structure)
(f (datum structure)))
(else
(cons (tree-map f (car (children structure)))
(tree-map f (cdr (children structure)))))))
这些是树的构造函数和选择器:
(define (make-node datum children)
(cons datum children))
(define (datum node)
(car node))
(define (children node)
(cdr node))
(define (leaf datum)
(make-node datum '()))
(define (leaf? node)
(null? (children node)))
对于我的测试用例,我使用这个数字树和一个函数,例如square:
(define number-tree
(make-node
'56
(list (make-node
'2
(children '(34 25 7 89)))
(make-node
'32
(list (make-node
'27
(children '(13 55 80)))
(make-node
'1098
(children '(45 785 98)))
(make-node '123 (children '(9046)))))
(make-node '23 (children '(1 9)))
(make-node '867
(children '(1 3 5 78)))
(make-node
'0
(list
(make-node '78 (children '(984)))
(make-node '45
(children '(23 46 78467)))
(make-node '3 (children '(2))))))))
我收到的错误消息类似于“cdr、违反合同、预期对”。到目前为止,我在Scheme中处理列表没有太多问题——我似乎收到了它们。但是翻译成树给我带来了一个问题——有一点我在原则上没有得到,这意味着我不断得到这些与树问题相关的错误消息。我试图继续使用抽象类型(树和节点),而不考虑列表。
我这样做对吗?我非常感谢任何帮助我理解我在与树木一起工作时所缺少的东西 名为
children
的过程是访问器,而不是构造函数。因此:
(make-node
2
(children '(34 25 7 89))
应该是:
(make-node 2
(list (leaf 34)
(leaf 25)
(leaf 7)
(leaf 89)))
你可以按照书中的方法制作叶子,也许像这样:
(define (leafs lst-values)
(map leaf lst-values))
(make-node 2 (leafs '(34 25 7 89)))
不是叶的树节点有值,如我的节点示例中的2,而一般树结构叶是除对之外的任何东西,对是具有两个子节点的节点。下面是一个树映射
,它在生成节点
生成的树上工作:
(define (tree-map proc tree)
(let aux ((tree tree))
(make-node (proc (datum tree))
(map aux (children tree)))))
请注意,对于
叶
节点(子树)
将是'()
,而(映射任何内容())
始终变为'(),以便生成节点
将生成一个新叶。递归是通过映射实现的,因为该树有多个子树,而树结构只有两个子树。由于结构严格,此树的值也可以是成对的。谢谢,这很有帮助。树图确实有用。很高兴能理解我在数字树上犯的错误。