简体   繁体   中英

Replicate A Given Element in a List in Scheme

So I'm writing a scheme function that takes in one element and one list and returns the list with the element replicated ie (replicate 'd '(abc 1 d)) should return '(abc 1 dd)) .

However all it returns is the original list whenever the element is not part of the list and the element when it is. I'm new to scheme and having trouble finding where my error is. I'd appreciate the help!

(define (replicate elmt set)
 (cond((null? set) '())
     ((member? elmt set)(replicate_helper elmt set))
     (else set)))

(define (replicate_helper elmt set)
    (cond (eq? (car set) elmt) (cons elmt set)
        (else (cons (car set)
                (replicate_helper elmt (cdr set))))))

Also member? is my function that returns #t when an element is in the list and #f when not. Here's what it looks like:

(define (member? elmt set)
 (cond ((null? set) #f)
    ((eq? elmt (car set)) #t)
    (else(member? elmt (cdr set)))))

It was a simple mistake: a couple of parentheses were missing in the first condition of replicate_helper . Simply substitute your implementation with this one:

(define (replicate_helper elmt set)
  (cond ((eq? (car set) elmt) (cons elmt set))
        (else (cons (car set)
                    (replicate_helper elmt (cdr set))))))

And it should work as expected:

(replicate 'd '(a b c 1 d))
=> '(a b c 1 d d)

(replicate 'x '(a b c 1 d))
=> '(a b c 1 d)

As an improvement, I suggest you replace eq? with equal? in replicate_helper and member? , see this post to understand why.

But wait, we can go even further: we don't need three procedures for solving this problem, a single procedure is enough if we're careful with the base cases - this is what I mean:

(define (replicate elmt set)
  (cond ((null? set) '())
        ((equal? (car set) elmt) (cons elmt set))
        (else (cons (car set)
                    (replicate elmt (cdr set))))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM