0
votes

How do you abstract find-string to generic-find-string so that the string comparison operation it uses is a parameter. Using local? or any other abstract functions?
My find-string via recursion,

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

I suppose we could use local (maybe not? it looks like map or filter too) and the contract of generic-find-string would be,

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

Then use this abstraction to define find-string-case-sensitive, which should operate the same way as the original find-string, and find-string-case-insensitive, which has the same contract as find-string but which ignores the case of alphabetic characters when comparing strings (i.e. the character a is considered the same as A and so on; non-alphabetic characters must still match exactly).

Any thoughts and suggestions? Thanks in advance.

1

1 Answers

2
votes

Abstracting the comparison away is just a matter of adding a third argument to be used as your n-ary comparison function:

(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

Then redefine find-string in terms of find-gen:

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

From there on I trust it is pretty straightforward for you to define all the variants you may require.