Inserting at arbitrary position in list in Scheme

时光毁灭记忆、已成空白 提交于 2020-01-14 02:58:10

问题


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

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.

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


回答1:


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))))))

For example:

(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)


来源:https://stackoverflow.com/questions/29124228/inserting-at-arbitrary-position-in-list-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!