1

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
)

私の関数の割り当て完了と選択-u は単体テストに合格します。引数代入は(make-hash)でハッシュテーブルmakeなので問題ないはずです。

私が抱えている問題は、再帰が false 以外の値を返さない場合 (有効な割り当てである必要があります)、ループの最後に false を返すことに関連していると思います。明示的な return ステートメントに相当するスキームはありますか?

4

1 に答える 1

0

あなたの質問への答えはイエスです:

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

これにより、関数の本体内から結果値を返すことができるように、終了 継続が設定されます。通常のSchemeの方法は、リターンフォームを最後のものとして置くことです。そのため、その値が返されます:

    (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節があります。

于 2013-11-08T09:32:02.620 に答える