在列表中运行长度编码符号

时间:2018-12-22 21:22:37

标签: scheme racket

我想问您寻求帮助,以打印下面的代码结果来解决我的任务。输入为:(run-length-encode '(1 1 2 2 3 3 4 4 a a b b)),它返回((2 . 1) (2 . 2) (2 . 3) (2 . 4)),但我希望有类似(2 1 2 2 2 3 2 4 2 a 1 b)的输出。我在做什么错了?

    (define (run-length-encode lst)
  (define (rle val-lst cur-val cur-cnt acc)
    (if (pair? val-lst)
        (let ((new-val (car val-lst)))
          (if (eq? new-val cur-val)
              (rle (cdr val-lst) cur-val (+ cur-cnt 1) acc)
              (rle (cdr val-lst) new-val 1 (cons (cons cur-cnt cur-val) acc))))
        (cons (cons cur-cnt cur-val) acc)))
         (if (pair? lst)
           (reverse (rle (cdr lst) (car lst) 1 '()))
           '()))

感谢您的帮助, 扬

0 个答案:

没有答案