[这是一个家庭作业问题]
到目前为止我所拥有的:
(define-struct freq [str num])
;Frequency is:
;- (make-freq str num)
.
; A ListOfStrings (LoS) is one of:
; - empty
; - (cons String LoS)
; A ListOfFrequency (LoS) is one of:
; - empty
; - (cons Frequency LoS)
; count-word
; LoF string -> (updated LoF)
; adds 1 to the frequency of string
; If there is no frequency for string, it should have 1
(define (count-word LoF s)
(cond [(empty? LoF)empty]
[else (cons[make-freq s (+(freq-num(first LoF))1)]
(rest LoF)))]))
Input:
(count-word(list(make-freq "hello" 1)(make-freq "world" 1))"hello")
Expected (and actual) Output:
(list(make-freq "hello" 2)(make-freq "world" 1))
Input:
(count-word(list(make-freq "hello" 1)(make-freq "world" 1))"world")
Expected Output:
(list(make-freq "hello" 1)(make-freq "world" 2))
Actual Output:
(list(make-freq "world" 2)(make-freq "world" 1))
据我所知,如果字符串输入与(freq-str(第一个LoF))相同,那么(freq-num(第一个LoF))应该更新(添加)1。但是,如果在LoF中不存在字符串输入,然后将其附加到freq-num为1的原始列表中。我该怎么做?谢谢!
[注意:我是一名初学者,我看到类似帖子的答案涉及lambda,我还不熟悉。]
答案 0 :(得分:0)
问题是你永远不会检查你正在更新频率的单词,你总是更新第一个单词。
(define (count-word LoF s)
(cond [(empty? LoF)empty]
[else (cons[make-freq s (+(freq-num(first LoF))1)] ; Unconditional
(rest LoF)))]))
您需要在列表中搜索单词,就像使用列表时一样,递归也很好。
(你最近可能已经看过或写过一些“在列表中搜索东西”的代码。)
对于非空列表,您需要两个递归案例 - 第一个元素是您正在计算的字符串,或者不是。 如果你找到它,那就做你现在正在做的事 如果您还没有找到它,请继续递归查看。
您还需要实现评论的代码,如果“字符串没有频率,则应该为1” 当我们到达空列表并且递归终止时,必须是这种情况。
我将添加一些实用程序函数,使函数本身更简洁:
(define (equal-str? s f)
(equal? s (freq-str f)))
(define (inc-freq f)
(make-freq (freq-str f) (+ (freq-num f) 1)))
(define (count-word LoF s)
(cond [(empty? LoF) (list (make-freq s 1))] ; Not found
[(equal-str? s (first LoF)) (cons [inc-freq (first LoF)] (rest LoF))] ; Found it
[else (cons <...> <...>)])) ; Keep looking
由于这是家庭作业,有趣的案例(<...>
)留作练习。