我正在尝试在方案中实现反向跟踪搜索。到目前为止,我有以下内容:

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

我的功能分配完整和Select-U通过单元测试。论点分配是(用力锤)的哈希桌制作,因此应该没关系。

我相信我遇到的问题与循环结束时返回错误有关,如果没有递归返回非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 具有非零值,如果没有,则检查 assignment 变量,但是无论如何,其返回的值无论如何都被忽略。也许那里还有更多的括号,/或 else 条款。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top