Loops 在Scheme中如何在循环结束时返回默认值?
我正在尝试在Scheme中实现回溯搜索。到目前为止,我有以下几点:Loops 在Scheme中如何在循环结束时返回默认值?,loops,scheme,backtracking,constraint-satisfaction,Loops,Scheme,Backtracking,Constraint Satisfaction,我正在尝试在Scheme中实现回溯搜索。到目前为止,我有以下几点: (define (backtrack n graph assignment) (cond (assignment-complete n assignment) (assignment) ) (define u (select-u graph assignment)) (define c 1) (define result 0) (let forLoop () (w
(define (backtrack n graph assignment)
(cond (assignment-complete n assignment) (assignment) )
(define u (select-u graph assignment))
(define c 1)
(define result 0)
(let forLoop ()
(when (valid-choice graph assignment c)
(hash-set! assignment u c)
(set! result (backtrack n graph assignment))
(cond ((not (eq? result #f)) result))
(hash-remove! assignment u)
)
(set! c (+ c 1))
(when (>= n c) (forLoop))
)
#f ; I believe this is where I'm having problems
)
我的功能分配完成并通过单元测试。参数赋值是一个hash表make with(make hash),因此应该可以
我相信我遇到的问题与在循环结束时返回false有关,如果没有递归返回非false值(应该是有效的赋值)。是否有一个与显式返回语句等效的方案?您的问题的答案是肯定的: 这将设置一个出口,以便您可以从函数体内部返回结果值。通常的方案方法是将您的返回表单作为最后一个表单,因此返回其值:
(let forLoop ()
(when (valid-choice graph assignment c)
(hash-set! assignment u c)
(set! result (backtrack n graph assignment))
(cond
((not (eq? result #f))
result)) ; the value of `cond` form is ignored
(hash-remove! assignment u))
; the value of `when` form is ignored
(set! c (+ c 1))
(if (>= n c) ; `if` must be the last form
(forLoop) ; so that `forLoop` is tail-recursive
;; else:
return-value) ; <<------ the last form's value
) ; is returned from `let` form
;; (let forLoop ...) must be the last form in your function
;; so its value is returned from the function
)
此代码不呼叫(分配完成n个分配)
。相反,它检查变量赋值完成
是否有非空值,如果没有,则检查赋值
变量,但在任何情况下,其返回值都会被忽略。可能缺少了更多的括号和/或else
子句
(let forLoop ()
(when (valid-choice graph assignment c)
(hash-set! assignment u c)
(set! result (backtrack n graph assignment))
(cond
((not (eq? result #f))
result)) ; the value of `cond` form is ignored
(hash-remove! assignment u))
; the value of `when` form is ignored
(set! c (+ c 1))
(if (>= n c) ; `if` must be the last form
(forLoop) ; so that `forLoop` is tail-recursive
;; else:
return-value) ; <<------ the last form's value
) ; is returned from `let` form
;; (let forLoop ...) must be the last form in your function
;; so its value is returned from the function
)
(cond (assignment-complete n assignment) (assignment) )