質問

スキームにバックトラッキング検索を実装しようとしています。これまでのところ、私は次のことを持っています:

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

私の関数assignment-completeおよび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