在Scheme列表中的任意位置插入 [英] Inserting at arbitrary position in list in Scheme

查看:100
本文介绍了在Scheme列表中的任意位置插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单,例如:(B D F)

I have a list with me, for example: (B D F)

我想在列表中的任意位置插入一个元素.例如,如果元素是A,我想将其插入B之前,如果元素C,我想将其插入B之后但D之前.

I want to insert an element at an arbitrary position in the list. For example, if the element is A, I want to insert it before B and if the element C, I want to insert it after B but before D.

是否可以在Scheme中列表的任意位置插入元素?

Is there any way to insert elements at an arbitrary position in a list in Scheme?

推荐答案

为此很容易实现一个功能:

It's easy to implement a function for this:

(define (insert-at new k lst)
  (cond ((null? lst)
         (list new))
        ((zero? k)
         (cons new lst))
        (else
         (cons (car lst)
               (insert-at new (sub1 k) (cdr lst))))))

例如:

(insert-at 'B 1 '(A))
=> '(A B)

(insert-at 'A 0 '(B D F))
=> '(A B D F)

(insert-at 'C 2 '(A B D F))
=> '(A B C D F)

这篇关于在Scheme列表中的任意位置插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆