문제

체계에서 백 트래킹 검색을 구현하려고합니다. 지금까지 나는 다음과 같습니다.

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

이것은 an을 설정합니다 출구 계속 함수의 본문 내부에서 결과 값을 반환 할 수 있도록합니다. 일반적인 체계 방법은 반품 양식을 마지막으로 배치하는 것입니다. 따라서 그 값은 반환됩니다.

    (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