简体   繁体   English

复制方案列表中的给定元素

[英]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)) . 所以我正在编写一个方案函数,该函数接受一个元素和一个列表,并返回带有复制元素的列表,即(replicate 'd '(abc 1 d))应该返回'(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. 是我的函数,当元素在列表中时返回#t,当元素不在列表中时返回#f。 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 . 这是一个简单的错误:一对夫妇括号中的第一个条件是失踪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? 作为改进,我建议您替换eq? with equal? equal? in replicate_helper and member? replicate_helpermember? , 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))))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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