【问题标题】:How do you abstract function to function in scheme您如何将功能抽象为方案中的功能
【发布时间】:2014-11-23 06:44:32
【问题描述】:

如何将find-string抽象为generic-find-string,使其使用的字符串比较操作是一个参数。使用本地?或任何其他抽象函数?
我的 find-string 通过递归,

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

我想我们可以使用 local (也许不是?它看起来也像 map 或 filter),而 generic-find-string 的合同是,

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

然后用这个抽象来定义find-string-case-sensitive,应该和原来的find-string一样操作,find-string-case-insensitive,和find-string-case-insensitive一样契约为 find-string 但在比较字符串时忽略字母字符的大小写(即字符 a 被认为与 A 相同,依此类推;非字母字符仍然必须完全匹配)。

有什么想法和建议吗?提前致谢。

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    抽象比较只是添加第三个参数用作 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))
    

    我相信从那时起,您可以非常简单地定义您可能需要的所有变体。

    【讨论】:

    • 嗯,这区分大小写的。如果你想不区分大小写,只需使用string-ci=? 而不是string=?(find-gen string-ci=? (list "A" "B" "C") "a") => #t(参见the Racket reference on strings)。
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2014-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多