将字符添加到频率列表 [英] Add a character to a frequency list

查看:65
本文介绍了将字符添加到频率列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有关霍夫曼编码的项目,但我陷入了困境,我不明白为什么我的代码无法正常工作.

I have a project about huffman coding, and I am stuck, I don't understand why my code is not working.

这是练习:

编写一个函数add1,给定一个字符,在频率列表中为其频率加1.如果该字符尚未出现在频率列表中,则会添加该字符.

Write a function add1 which, given a character, adds 1 to its frequency in a frequency list. If the character is not yet in the list of frequencies, it is added.

(add1 "e" '(("l" 1) ("e" 2) ("x" 1)))       →          (("l" 1) ("e" 3) ("x" 1)) 
(add1 "e" '(("a" 4) ("b" 3)))               →          (("a" 4) ("b" 3) ("e" 1)) 

我写的是

(define add1
  (lambda (c l) 
    (if (null? l)
        '()
        (if (member? c l)
            (if (equal? c (caar l))
                (+ 1 (cadar l))
                (add1 c (cdr l)))
            (append l '((c 1)))))
        ))

结果:

(list (list "l" 1) (list "e" 2) (list "x" 1) (list 'c 1))

推荐答案

调用add1该过程是一个坏主意,该过程与同名的内置过程发生冲突.尝试以下方法:

It's a bad idea to call add1 the procedure, that clashes with a built-in procedure of the same name. Try this instead:

(define add-one
  (lambda (c l)
    (cond ((null? l)
           (list (list c 1)))
          ((equal? (caar l) c)
           (cons (list c (+ 1 (cadar l))) (cdr l)))
          (else
           (cons (car l) (add-one c (cdr l)))))))

看看如何,如果我们到达一个空列表,这是因为在列表中找不到该字符,因此我们必须在末尾添加它.其他两种情况是不言自明的:字符是当前字符,还是字符在列表的其余部分中.通过以这种方式编写解决方案,就不必使用member?.它可以按预期工作:

See how, if we reach an empty list, it's because the character wasn't found in the list, so we must add it at the end. The other two cases are self-explanatory: either the character is the current one, or the character is in the rest of the list. By writing the solution in this way, it's not necessary to use member?. It works as expected:

(add-one "e" '(("l" 1) ("e" 2) ("x" 1)))
=> (("l" 1) ("e" 3) ("x" 1)) 

(add-one "e" '(("a" 4) ("b" 3)))
=> (("a" 4) ("b" 3) ("e" 1))

这篇关于将字符添加到频率列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆