如何在方案中的循环端返回默认值



我正在尝试在 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 ()
        (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
)

我的函数赋值完成和选择你通过单元测试。参数赋值是一个哈希表,所以应该没问题。

我相信我遇到的问题与循环结束时返回 false 有关,如果没有递归返回非 false 值(这应该是一个有效的赋值)。是否有与显式返回声明等效的方案?

您的问题的答案是肯定的

(define (foo ...)
  (call-with-current-continuation
    (lambda (return)
      ...... ; here anywhere inside any sub-expression 
      ...... ; you can call (return 42)
      ...... ; to return 42 from `foo` right away
    )))

这将设置一个退出延续,以便您可以从函数主体内部返回结果值。通常的方案方法是将您的返回表单作为最后一个,因此返回其值:

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

此代码不会调用(assignment-complete n assignment) 。相反,它会检查变量assignment-complete是否具有非 null 值,如果没有,它会检查assignment变量,但无论如何,它的返回值都会被忽略。也许那里缺少更多的括号,和/或else条款。

相关内容

  • 没有找到相关文章

最新更新