交换方案列表中的两个元素 [英] Swap two elements in list in Scheme
本文介绍了交换方案列表中的两个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在Scheme语言的列表中的已输入索引上切换2个元素.例如:
I need to switch 2 elements on entered indexes in list in Scheme lang. For example:
(交换索引0 3'(1 2 3 4 5))
(swap-index 0 3 '(1 2 3 4 5))
(4 2 3 1 5)
(4 2 3 1 5)
有人可以帮忙吗?提前致谢! :)
Can someone help? Thanks in advance! :)
推荐答案
这里是clojure中的解决方案.我希望算法会有所帮助.
Here is solution in clojure. I hope algorithm would be helpful.
(defn split [idx lst]
(let [lst-rest (drop idx lst)]
[(take idx lst) (first lst-rest) (rest lst-rest)]))
(defn swap-index [idx1 idx2 lst]
(let [[lst1 e1 lst] (split idx1 lst)
[lst2 e2 lst3] (split (dec (- idx2 idx1)) lst)]
(concat lst1 [e2] lst2 [e1] lst3)))
=> (swap-index 0 3 [1 2 3 4 5])
(4 2 3 1 5)
这篇关于交换方案列表中的两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文