2

私は Dr. Racket を使用しており、言語は Pretty Big で、単純な二分探索木を "in?" で作成しようとしています。値が二分探索木にあるかどうかを返すメソッド。あらゆる種類の検索ツリー (文字列、int などを含むかどうか) を受け入れて、一般的である必要がありますが、このエラー メッセージが表示されて気が狂いそうです。コードは次のとおりです。

編集:: 現在は動作しますが、数字以外では動作しません (または、少なくとも文字列では動作しません)。新しい問題:

(define (bstsearch tree value)
  (cond 
  ((null? tree) #f)
  ((< value (car tree))
      (bstsearch  (cadr tree) value))
  ((> value (car tree))
      (bstsearch (caddr tree) value))
  ((= value (car tree))
      #t)
  ))

私が受け取っているエラーは言う:

<: expects type <real number> as 1st argument, given: "horse"; other arguments were: "horse"

使用時:

 (bstsearch '("horse" ("cow" () ("dog" () ())) ("zebra" ("yak" ()()) ())) "horse")

入力として。

4

4 に答える 4

3

新しい問題に関して、< と > は数字に対してのみ機能します。簡単な解決策は、比較関数を引数として bstsearch プロシージャに渡すことです。

また、前述のとおり、コードは正しくインデントしてください。

于 2010-12-05T05:23:44.097 に答える
2

1 つの問題は、 < と > が逆になっていることです。左のサブツリーを小さくしたい場合、(< value (car tree)) は (cadr tree) で再度呼び出す必要があります。

また、(#t) の代わりに #t を使用する必要があります。

于 2010-12-05T04:25:48.250 に答える
2

引数を別の括弧のセットでラップしないでください。

(bstsearch  (cadr tree) value)

それ以外の

(bstsearch  ((cadr tree) value))
于 2010-12-05T04:00:30.243 に答える
1

Your newly faced problem is because of your comparer function "=". If you change that with "equal?" function it should be generic and work in any kind of data. Comparers also should change if you want to make it generic. You must take it from user as input so generic version of it should be:

(define (bstsearch tree value comparer)

(cond 

((null? tree) #f)

  ((equal? value (car tree)) #t)

  ((comparer value (car tree))
      (bstsearch  (cadr tree) value))

  ((not (comparer value (car tree)))
      (bstsearch (caddr tree) value))

  ))
  • Comparer function should be in format of (X X -> boolean), "<", ">", "string<?" are built in examples but you can write your own comparer for your own data structure too

  • Note that the equal condition is on the 2. line. I hope this helps :)

于 2011-04-06T09:05:13.657 に答える