【发布时间】:2017-11-07 00:44:29
【问题描述】:
所以对于我的代码,我需要编写一个函数来返回字符串中单词的频率。 到目前为止,我有以下代码:
(define (num-occurs sym lst)
(define (counter sym lst count)
(cond ((null? lst) count)
((equal? (car lst) sym) (counter sym (cdr lst) (+ 1 count)))
(else (counter sym (cdr lst) count))))
(counter sym lst 0))
(define (remove-all elem lst)
(if (null? lst)
'()
(if (equal? elem (car lst))
(remove-all elem (cdr lst))
(cons (car lst) (remove-all elem (cdr lst))))))
(define (word-frequencies str)
(let ((lst (string->list str)))
(if (null? lst)
'()
(append (list (cons (car lst) (num-occurs (car lst) lst)))
(word-frequencies (remove-all (car lst) (cdr lst)))))))
当我给它一个输入时:(word-frequencies "hi there person hi")
我收到此错误。 字符串->列表:违反合同 预期:字符串? 给定: (#\i #\space #\t #\e #\r #\e #\space #\p #\e #\r #\s #\o #\n #\space #\i)
帮助将不胜感激它为什么这样做? 我希望我的最终输出看起来像。
((嗨。2)(那里。1)(人。1))
【问题讨论】:
-
请注意
string->list返回的是字符列表而不是符号。所以(string->list "hi")返回'(#\h #\i)。 -
你知道我怎么能直接从一个字符串变成一个列表吗?所以它就变成了 '(hi there person hi)。
-
您可以拆分字符串并将
string->symbol映射到字符串的结果列表中,即。(map string->symbol (string-split "hi there person hi")). -
@M.Maric 看到我的回答。它应该是直截了当的。