Scheme run length encoding

不问归期 提交于 2019-12-02 11:19:42

You need a helper function that has the count as additional argument. You check the first two elements against each other and recurse by increasing the count on the rest if it's a match or by consing a match and resetting count to 1 in the recursive call.

Here is a sketch where you need to implement the <??> parts:

(define (encode lst)
  (define (helper lst count)
    (cond ((null? lst) <??>)
          ((null? (cdr lst)) <??>))
          ((equal? (car lst) (cadr lst)) <??>)
          (else (helper <??> <??>))))
  (helper lst 1))

;; tests
(encode '())              ; ==> ()
(encode '(1))             ; ==> ((1 1))
(encode '(1 1))           ; ==> ((1 2))
(encode '(1 2 2 3 3 3 3)) ; ==> ((1 1) (2 2) (3 4))

Using a named let expression

This technique of using a recursive helper procedure with state variables is so common in Scheme that there's a special let form which allows you to express the pattern a bit nicer

(define (encode lst)
  (let helper ((lst lst) (count 1))
    (cond ((null? lst) <??>)
          ((null? (cdr lst)) <??>))
          ((equal? (car lst) (cadr lst)) <??>)
          (else (helper <??> <??>)))))

Comments on the code in your question: It has excess parentheses..

((append ....)) means call (append ....) then call that result as if it is a function. Since append makes lists that will fail miserably like ERROR: application: expected a function, got a list.

(n) means call n as a function.. Remember + is just a variable, like n. No difference between function and other values in Scheme and when you put an expression like (if (< v 3) + -) it needs to evaluate to a function if you wrap it with parentheses to call it ((if (< v 3) + -) 5 3); ==> 8 or 2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!