在Lisp中搜索BST
我正在编写一个程序,引导机器人通过BST到达目标编号。该程序有两个输入参数,一个目的地为整数,另一个地图表示机器人可以遵循的所有路径 ie:(机器人64’(53(()(64())) 其中64是目的地,53(()(64())是BST 我需要帮助写这个方法。这是我最初的工作在Lisp中搜索BST,lisp,scheme,binary-search-tree,Lisp,Scheme,Binary Search Tree,我正在编写一个程序,引导机器人通过BST到达目标编号。该程序有两个输入参数,一个目的地为整数,另一个地图表示机器人可以遵循的所有路径 ie:(机器人64’(53(()(64())) 其中64是目的地,53(()(64())是BST 我需要帮助写这个方法。这是我最初的工作 (define (robot goal map) (let ((x (car map))) (define empty? '()) (display x) (cond (empty? x)
(define (robot goal map)
(let ((x (car map)))
(define empty? '())
(display x)
(cond (empty? x)
(robot goal (cadr map)))
(cond ((= goal x)) (display x))
(cond (< x goal)
(robot goal (cadr map)))
(cond (> x goal)
(robot goal (caddr map)))
;(display "NULL")
)
)
(定义(机器人目标地图)
(让((x(汽车地图)))
(定义为空?'())
(显示器x)
(cond(空?x)
(机器人目标(cadr地图)))
(条件(=目标x))(显示x))
(条件(x目标)
(机器人目标(caddr地图)))
;(显示“空”)
)
)
它应该在BST中搜索,如果找到路径,它将打印(找到:#T#T…#T#),如果您的目的地在树中而不是根(#是位置号,T是L或R,表示您在位置#左转或右转)
注意:我直到昨天才使用过Lisp,如果我有点迷路,那么很抱歉。对于当前的问题,过程的结构不正确-您没有正确处理递归,并且没有为请求的输出构建一个列表。此外,这不是使用
cond
的正确方法,您不应该重新定义如果现有的过程map
和empty?
。此外,如果元素不在树中会发生什么?在确定树不为空之前,您不能执行(汽车树)
我将提供解决方案的正确结构,并给您一些提示,这样您就可以自己计算出解决方案,如果在树中找不到元素,我们将返回一个列表,其中最后一个位置的值为notfound
(define (robot goal tree)
(cond ((empty? tree) ; if the tree is empty
'(not-found)) ; return special value indicating it
((= <???> goal) ; if the current element is goal
<???>) ; return a list with current element
((< goal <???>) ; if goal is less than current element
(cons <???> ; cons current element
(cons <???> ; with L and advance the recursion
(robot goal <???>)))) ; going to the left
(else ; otherwise
(cons <???> ; cons current element
(cons <???> ; with R and advance the recursion
(robot goal <???>)))))) ; going to the right
对于当前的问题,过程的结构是不正确的-您没有正确地处理递归,并且没有为请求的输出构建一个列表。另外,这不是使用
cond
的正确方法,您不应该重新定义现有过程map
和empty?
。还有,什么是h如果元素不在树中,则出现?在确定树不为空之前,无法执行(汽车树)
我将提供解决方案的正确结构,并给您一些提示,这样您就可以自己计算出解决方案,如果在树中找不到元素,我们将返回一个列表,其中最后一个位置的值为notfound
(define (robot goal tree)
(cond ((empty? tree) ; if the tree is empty
'(not-found)) ; return special value indicating it
((= <???> goal) ; if the current element is goal
<???>) ; return a list with current element
((< goal <???>) ; if goal is less than current element
(cons <???> ; cons current element
(cons <???> ; with L and advance the recursion
(robot goal <???>)))) ; going to the left
(else ; otherwise
(cons <???> ; cons current element
(cons <???> ; with R and advance the recursion
(robot goal <???>)))))) ; going to the right
我都弄明白了。谢谢你的帮助!我都弄明白了。谢谢你的帮助!