我正在尝试编写一个函数,该函数的计算结果是输入字符串str中不同字符的数量。例如,(distinct-char "eeeiicczz")会返回4,我需要一些代码方面的帮助。这就是我拥有的。
(define string-contains
(lambda (str char)
(if (equal? str "")
#f
(if (char=? (string-ref str 0) char)
#t
(if (not (char=? (string-ref str 0) char))
(string-contains (substring str 1 (string-length str)) char))))))
(define unique-chars
(lambda (str)
(cond
((equal? str "") "")
((equal? (string-length str) 1) (string-ref str 0))
(else
(if (equal? (string-contains (substring str 1 (string-length str)) (string-ref str 0)) #t)
(unique-chars (substring str 1 (string-length str)))
(string-append (substring str 0 1) (substring str 1 (string-length str))))))))
(define distinct-char
(lambda (str)
(string-length (unique-chars str))))我只能使用这些内置函数:
(if x y z), (cond ...),
(read)
(string-length x)
(string-ref str x)
(substring x y)
(string-append x y)
(equal? x y), (char=?)
(remainder x y), (quotient x y)
(max ...), (min ...)
(+ x y), (- x y), (* x y), (/ x y)
(> x y), (< x y), (<= x y), (>= x y)
(and x y), (or x y), (not x y) 发布于 2010-09-26 09:21:43
由于可以将字符串转换为列表,因此使用内置的列表函数会容易得多。(注意:以下代码是在球拍中。因为它很像Scheme,所以我假设这些函数是存在的。如果他们不检查你的文档中是否有类似的东西)
(define (distinct-char str)
(length (remove-duplicates (string->list str))))这是一个您可以填写的模板。将注释替换为您认为在每种情况下应该发生的情况。祝好运!
(define (empty-string? str)
( #| What property does an empty string have? Add a simple boolean expression here. |# )
(define (char-exists? str char)
(cond
[(empty-string? str) ( #| If the string is empty, does the character exist? |# )]
[else ( #| Check the first character in the string. If it is what we're looking for
we're done! If it's not call this function on the rest of the string. |# )]))
(define (unique-chars str)
(cond
[(empty-string? str) ( #| What should you return if the string is empty? |# )]
[(equal? (string-length str) 1) ( #| What should you return if the string is one character long? |# )]
[else ( #| If the character at the beginning of the string exists in the rest of the string, ignore it
and preform recursion on the rest of the string. If it doesn't, append the character to
the result of this function on the rest of the string. |# )]))
(define (distinct-char str)
(string-length (unique-chars str)))发布于 2010-09-26 09:31:32
你在方案中学习东西的原因之一是它训练你自己构建有用的构建块,然后将这些构建块连接在一起。
在这种情况下,我推荐的一般方法是编写一个函数:
(string-contains str ch)这将根据str是否包含字符ch返回#t或#f,然后使用该字符定义函数:
(unique-chars str)这将返回一个包含str中唯一字符的字符串(您扫描str,构建您的答案,并在每个地方查看下一个字符是否已经在您构建的答案字符串中,如果没有,则将其添加到您的答案字符串中)。
然后,您想要的函数就是
(string-length (unique-chars str))发布于 2010-09-26 09:21:52
您可以保留并传递您以前遇到的每个不同字符的列表。这样,每次你检查一个新字符时,你就会在列表中查找它,看看你以前是否见过它。如果它不在你的列表中,那么它是一个新字符,你可以将它添加到你的列表中。
家庭作业问题,所以我不会在答案中写代码。
https://stackoverflow.com/questions/3796158
复制相似问题