2014-11-22 70 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