Search code examples
schemerun-length-encodingreplit

Run length encoding of the symbols in list with using scheme language


I am trying to find frequency of the letters in a list with using scheme language but I can not do it for 4 days, and code must be work in repl.it

For example, our list is

 (a a a a b c c a a d e e e e)

our output should be

(4 a ) b ( 2 c ) ( 2 a ) d ( 4 e )

I have code which can also work on 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)))))))))

Here is the code that I try


Solution

  • I have code which can also work on 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)))))))))