2014-11-22 65 views
0

中如何抽象查找字符串通用查找字符串使得它使用的字符串比較操作是一個參數。使用本地?或任何其他抽象功能?
查找字符串通過遞歸如何抽象功能在方案

;; find-string: Lof[string] string -> Boolean 
;; true if and only if the given string was in the list 

(define (find-string los s) 
    (cond 
     [(empty? los) false] 
     [(cons? los) (cond 
        [(string=? s (first los)) true] 
        [else (find-string (rest los) s)])])) 

(check-expect(find-string (list "a" "b" "c") "a") true) 
(check-expect(find-string (list "a" "b") "f") false) 
(check-expect(find-string empty "a") false) 

我想我們可以用本地(也許不是?它看起來像地圖或過濾太)和通用-找到字符串的合同是,

;; generic-find-string: (Lof[string] string -> Boolean) Lof[string] -> Boolean 
;; true if and only if the given string was in the list 

然後使用這個抽象定義查找字符串區分大小寫,應操作方式爲原始查找字符串相同,並找到字符串,不區分大小寫,WHI ch與find-string具有相同的約定,但在比較字符串時會忽略字母字符的情況(即,角色a被認爲與A相同等等;非字母字符必須完全匹配)。

有什麼想法和建議嗎?提前致謝。

回答

2

抽象的比較遠只是增加了第三個參數的事項作爲您的n元對比功能:

(define (find-gen op los s) 
    (cond 
     [(empty? los) false] 
     [(cons? los) (cond 
        [(op s (first los)) true] 
        [else (find-gen op (rest los) s)])])) 

(find-gen string=? (list "a" "b" "c") "a") 
=> #t 
(find-gen string=? (list "a" "b") "f") 
=> #f 
(find-gen string=? empty "a") 
=> #f 

然後在find-gen方面重新定義find-string

(define (find-string los s) 
    (find-gen string=? los s)) 

從那裏開始,我相信你很容易定義你可能需要的所有變體。

+0

謝謝。大小寫如何? – ads27 2014-11-25 00:10:28

+0

那麼,這是_is_區分大小寫的情況。如果你想不區分大小寫,只需使用'string-ci =?'而不是'string =?':'(find-gen string-ci =?(list「A」「B」「C」)「a」 )'=>'#t'(見[關於字符串的球拍參考](http://docs.racket-lang.org/reference/strings.html))。 – xbug 2014-11-25 17:24:27

+0

謝謝!非常有幫助。 – ads27 2014-11-25 19:02:40