我寫了下面的功能find-index
在列表中搜索:現在需要幫助的球拍
(: finind : (Listof Integer) Integer -> (Option Integer))
;; helper function for find-index
(define (finind a b)
(let loop ((a a) (c 0))
(cond
((empty? a) 'None)
((equal? (first a) b) (Some c))
(else (loop (rest a) (add1 c))))))
(: find-index : (Integer -> Boolean) (Listof Integer)
-> (Option (Pr (Option Integer) Integer)))
;; return the first item to pass the test, if there is one,
;; along with its (0-based) index
(define (find-index f x)
(match x
('() 'None)
((cons hd '())
(if (f hd) (Some (Pr (finind x hd) hd)) 'None))
((cons hd tl)
(if (f hd) (Some (Pr (finind x hd) hd))
(find-index f tl)))))
,finind
作品完美自身,但是當我find-index
使用它,它只是還給(Some 0)
。
(finind (list 45 41 9) 9)
的結果是(Some 2)
。
但是,(find-index (lambda ([t : Integer]) (< t 10)) (list 45 41 9))
的結果是(Some (Pr (Some 0) 9))
,即使它應該是(Some (Pr (Some 2) 9))
。
所以我知道這可能是因爲我有(finind x hd)
來顯示我的索引,因爲它的hd
它不會改變。但是,我如何解決這個問題?我一直在努力,但徒勞無功。有人可以幫忙嗎?謝謝!
在上一個cond術語謂詞是假的時候你是遞歸到'find-index',你不會以任何方式傳遞索引偏移量,所以它不知道這是你第三次做這件事。也許換一個索引並使用它可以解決您的問題。 – Sylwester
我不明白。你能給個例子嗎? – testomg
你沒有把''(45 41 9)'傳遞給'finind',你傳遞的第一個尾部滿足'f',即'(9)'。 – molbdnilo