Racket 球拍函数递归
你好,我是一名学生,目前正试图在Dr racket中创建一个函数,其目的是 选择字母后,它会将其转换为下划线 字符串(单词)字符串(字母)->字符串(答案/下划线) 我只能用一个字母as实现这一点,这使得第二个检查为真,我不知道如何处理多个字母Racket 球拍函数递归,racket,Racket,你好,我是一名学生,目前正试图在Dr racket中创建一个函数,其目的是 选择字母后,它会将其转换为下划线 字符串(单词)字符串(字母)->字符串(答案/下划线) 我只能用一个字母as实现这一点,这使得第二个检查为真,我不知道如何处理多个字母 (check-expect(underscore "william""li")"_illi__")) (check-expect(underscore "william" "l")"__ll___)) 我的代码: (define (anti-omit
(check-expect(underscore "william""li")"_illi__"))
(check-expect(underscore "william" "l")"__ll___))
我的代码:
(define (anti-omit word letter)
(cond[(string=? word letter)letter]
[(= 1 (string-length word))"_"]
[else
(string-append
(anti-omit (substring word 0 1)letter)
(anti-omit (substring word 1)letter))]))
这是一个带有目的声明、签名和测试的存根:
;; String String -> String
;; keeps all letters that occur in l, replaces with "_" otherwise
(check-expect (anti-omit "william" "li") "_illi__")
(check-expect (anti-omit "william" "l") "__ll___")
(define (anti-omit w l)
"")
由于您使用的是学生语言,并且正如您在问题标题中建议的,您希望在数据中重复出现。。。您需要一个递归数据定义:
;; String is one of:
;; - ""
;; - (string-append 1String String)
完成此函数的定义:
;; String -> String
;; is str equal to "" ?
(define (string-empty? str)
...)
(define (anti-omit w l)
(map-str (λ (x) (if (member-str x l) x "_")) w))
其他两个函数(对应于列表的rest和first)的更严格的数据定义:
您需要完成的其他一些功能:
;; NEString -> String
;; remove the first 1String from str
(define (string-rest str)
...)
;; NEString -> String
;; the first 1String form str
(define (string-first str)
...)
现在,您可以在字符串上生成如下函数:
;; [1String -> 1String] String -> String
;; Applies the function f on each 1String in s
(define (map-str f s)
(cond [(string-empty? s) ""]
[else (string-append (f (string-first s)) (map-str f (string-rest s)))]))
同样,完成此定义:
;; 1String String -> Boolean
;; is does 1String occur in String?
(define (member-str e l)
...)
我们的“愿望清单”已完成,我们可以组成助手完成最终功能:
;; String -> String
;; is str equal to "" ?
(define (string-empty? str)
...)
(define (anti-omit w l)
(map-str (λ (x) (if (member-str x l) x "_")) w))
使用explode和Inclode的类似版本,不需要我们定义的任何函数(将其用作参考实现):