我正在尝试使用方案语言在列表中查找字母的出现频率,但是我无法在4天内这样做,并且代码必须在repl.it中有效
例如,我们的列表是
(a a a a b c c a a d e e e e)
我们的输出应为
(4 a)b(2 c)(2 a)d(4 e)
谢谢...
答案 0 :(得分:1)
折叠列表,从一个空列表开始作为累加器。对于每个项目,请检查:如果累加器为空,则添加该项目(隐式计数为1)。如果累加器的前面有一个与之匹配的物品,则用该物品的计数2替换它。如果累加器的前端有一对与此匹配,则将其计数加一。否则,添加该项(隐式计数为1)。
(define (count-occurrences lat)
; Get the results in the order of the input list
(reverse
(fold (lambda (item acc)
(cond
; Start off by counting the first item
((null? acc)
(cons item acc))
; If the previous item was this one, set its count to 2
((and (atom? (car acc))
(eqv? item (car acc)))
(cons (list 2 item)
(cdr acc)))
; If there has been a run of this item, increment the count by 1
((and (pair? (car acc))
(eqv? item (cadar acc)))
(cons (list (+ 1 (caar acc)) item)
(cdr acc)))
; The previous item was not this one, so start counting this one now
(else
(cons item acc))))
'()
lat)))
fold
函数通常需要srfi-1
。
答案 1 :(得分:0)
我有可以在repl.it上运行的代码
(define (countW list1)
(if (null? list1)
'()
(let ((reserv (list 1)))
(let loop ((source reserv)
(elter (car list1))
(counter 1)
(list1 (cdr list1)))
(if (and (not (null? list1))
(equal? elter (car list1)))
(loop source elter (+ counter 1) (cdr list1))
(begin
(set-cdr! source (list (if (= 1 counter) elter (list elter counter))))
(if (null? list1)
(cdr reserv)
(loop (cdr source) (car list1) 1 (cdr list1)))))))))