1

我不知道如何在列表中的 n 位置附加一个元素。例如:

(insert-at new k lis)
(insert-at ’N 2 ’(a b c d e f))
=>
’(a b N c d e f)

没关系?:

(define (insert-at new k lis)
  (cond (( null? lis)
         (list new))   
        (zero? k   
         (cons new lis))   
        (else       
         (cons (car lis)
               (insert-at new (- k 1) (cdr lis))))))
4

4 回答 4

4

我会给你一些提示 - 因为这看起来像家庭作业,我不能给你一个直接的答案,如果你通过自己的方式得出解决方案会更有用。填空:

(define (insert-at new k lis)
  (cond (<???>       ; if the list is empty
         <???>)      ; return a list with the single element `new`
        (<???>       ; if `k` is zero
         <???>)      ; cons `new` with the list
        (else        ; otherwise
         (cons <???> ; cons the lists' current element and
               (insert-at new <???> <???>))))) ; advance the recursion

请注意,这里的“推进递归”意味着传递列表的其余部分并将k索引递减一个单位。k一旦索引为零或到达列表的末尾,我们就完成了。不要忘记测试程序:

(insert-at 'N 2 '(a b c d e f))
=> '(a b N c d e f)

(insert-at 'N 0 '(a b c))
=> '(N a b c)

(insert-at 'N 3 '(a b c))
=> '(a b c N)
于 2013-03-11T19:54:01.797 回答
2

如果你有两个功能:

  1. take-n - 作为列表返回前 N 个元素,并且
  2. last-n - 作为列表返回最后 N 个元素

那么你可以写:

(define (insert-at value index list)
  (let ((len (length list)))
    (assert (<= 0 index len))
    (append (take-n index list)
            (list value)
            (last-n (- len index) list))))
于 2013-03-11T20:11:35.350 回答
1

(DEFUN INS-ELEM(第 N 项列表)

(条件

((< Nth 1) (ERROR "Index too small ~A" Nth))

((= Nth 1) (CONS 项目列表))

((ENDP 列表)(错误“索引太大”))

(T (CONS (FIRST list) (INS-ELEM (1- Nth) item(REST list))))))

然后,只需调用 (INS-ELEM 2 'A '(BCDEF)) 并自己查看结果。

祝你好运!

于 2016-05-04T09:49:11.040 回答
0

#lang 球拍

(define (insert-at Index item lst)

(cond

[(< Index 1) (error "Index too small: " Index)]

[(= Index 1) (cons item lst)]

[(> Index (length lst)) (error "Index too big: " Index)]

[else (cons (first lst) (insert-at (- Index 1) item (rest lst)))]))

用户3660248

您关于如何解决此问题的想法似乎是正确且有意义的,但是您在 Racket 中的实现是不正确的,我修复了它,现在它可以工作了:)

于 2018-12-28T17:59:15.683 回答