替换方案

时间:2016-02-21 00:49:36

标签: list scheme

我的代码如下所示:

    (define replaceNth
      (lambda (nth item list1)
        (cond [(and (= nth 1) (eqv? (pair? list1) #f)) (cons item (cdr list1))] ;; If nth = 1 and there is more to the list, replace element at that location and add rest of list
              [(= nth 1) item] ;; if nth = 1 and there is no more list to add after, return item
              [else (list (car list1) 'derp (replaceNth (- nth 1) item (cdr (list list1))))]))) ;else decrement nth, and traverse rest of list

但是当我用这样的话来称呼它时:

    > (replaceNth 2 'q (list 'a 'b))

结果应为:

    (a b)

相反,我得到一个关于将不是一对的东西传递到第一个条件的错误,即使我在开头检查一个和一个语句来查看它是否是一对。

cdr: contract violation
expected: pair?
given: ()

我想我可能会错过陈述或写错了陈述。

*编辑:我原来的代码是这样的:

(define replaceNth
  (lambda (nth item list1)
    (cond [(= nth 1) (cons item (cdr list1))] ;; If nth = 1 replace element at that location and add rest of list
          [else (list (car list1) (replaceNth (- nth 1) item (cdr (list list1))))]))) ;else decrement nth, and cons/ recursively call replaceNth on rest of list

但我仍然得到同样的错误,我不明白因为,当我输入这个:

> (cons 'derp (cdr (cdr (list 'a 'b))))

我明白了:

> (derp)

这意味着当我在上面的代码中做类似的事情时,它不应该有问题。

2 个答案:

答案 0 :(得分:0)

您的功能必须始终返回列表。

您的中间情况不会返回列表;它返回替换值。我相信你想要返回list1,因为你的第一个案例处理你的计数器所说的替换列表的头部并且有一个头要被替换,所以第二种情况是没有头的地方替换。

答案 1 :(得分:-1)

我明白了,这是我的最终代码:

(define replaceNth
  (lambda (nth item list1)
    (cond [(= nth 1) (cons item (cdr list1))] ;; If nth = 1 replace element at that location and add rest of list
          [else (cons (car list1) (replaceNth (- nth 1) item (cdr list1)))]))) ;else decrement nth, and cons/ recursively call replaceNth on rest of list

输入:

(replaceNth 2 'q (list 'a 'b))

输出:

(a q)
相关问题