Removing duplicate characters from a string in a pattern

I tried this question for a long time, but not very far from it. The question is to create a string in which all duplicate characters from the entered string are replaced with one instance of the character.

For instance,

(remove-repeats "aaaab") => "ab"
(remove-repeats "caaabb aa") => "cab a"

Since I am trying to do this using cumulative recursion, I have:

(define (remove-repeats s) 
  (local
    [(define (remove-repeats-acc s1 removed-so-far)
      (cond
        [(empty? (string->list s1))""]
        [else 
         (cond
           [(equal? (first (string->list s1)) (second (string->list s1))) 
         (list->string (remove-repeats-acc (remove (second (string->list s1)) (string->list s1)) (add1 removed-so-far)))]
           [else (list->string (remove-repeats-acc (rest (string->list s1)) removed-so-far))])]))]
    (remove-repeats-acc s 0)))

But that does not seem right. Please help me change this to work.

Thank!

+3
source share
2 answers

Lines are a bit annoying to work with, so we wrap it around a work function that processes lists. In this way, we can avoid unrest throughout the world.

(define (remove-repeats str)
  (list->string (remove-repeats/list (string->list str))))

Now we can define the remove-repeat / list function using direct recursion:

(define (remove-repeats/list xs)
  (cond
    [(empty? xs) xs]
    [(empty? (cdr xs)) xs]
    [(equal? (car xs) (cadr xs)) (remove-repeats/list (cdr xs))]
    [else (cons (car xs) (remove-repeats/list (cdr xs)))]))

, :

(define (remove-repeats str)
  (list->string (remove-repeats/list-acc (string->list str) '())))

(define (remove-repeats/list-acc xs acc)
  (cond
    [(empty? xs) (reverse acc)]
    [(empty? (cdr xs)) (reverse (cons (car xs) acc))]
    [(equal? (car xs) (cadr xs)) (remove-repeats/list-acc (cdr xs) acc)]
    [else (remove-repeats/list-acc (cdr xs) (cons (car xs) acc))]))
+4

, , Typed Racket:

#lang typed/racket
(: remove-repeats : String -> String)
(define (remove-repeats s)
  (define-values (chars last)
    (for/fold: ([chars : (Listof Char) null] [last : (Option Char) #f])
      ([c (in-string s)] #:when (not (eqv? last c)))
      (values (cons c chars) c)))
  (list->string (reverse chars)))
+1

All Articles