按索引交换列表中的两个元素 [英] Swap two elements in a list by its indices
问题描述
有什么方法可以交换列表中的两个元素,如果我知道关于这些元素的唯一信息就是它们出现在列表中的位置。
要更具体一点,我正在寻找这样的东西:
swapElementsAt :: Int - > Int - > [Int] - > [b]
表现如下:
> swapElementsAt 1 3 [5,4,3,2,1] - 交换第一个和第三个元素
[3,4,5,2,1]
我认为内置函数可能存在于Haskell中,但我无法找到它。
Haskell没有这样的功能,主要是因为它有点不起作用。你真的想要实现什么?
你可以实现你自己的版本(也许有更习惯写法的方法)。请注意,我假设 i< j
,但是扩展函数以正确处理其他情况将是微不足道的:
swapElementsAt :: Int - > Int - > [a] - > [a]
swapElementsAt i j xs = let elemI = xs !!我
elemJ = xs !! (j + 1)xs)
right = drop(j + 1)xs
in left ++ [elemJ] ++ middle ++ [elemI] ++ right
Is there any way to swap two elements in a list if the only thing I know about the elements is the position at which they occur in the list.
To be more specific, I am looking for something like this:
swapElementsAt :: Int -> Int -> [Int] -> [Int]
that would behave like that:
> swapElementsAt 1 3 [5,4,3,2,1] -- swap the first and third elements
[3,4,5,2,1]
I thought that a built-in function for this might exists in Haskell but I wasn't able to find it.
Haskell doesn't have such a function, mainly because it is a little bit un-functional. What are you actually trying to achieve?
You can implement your own version of it (maybe there is a more idiomatic way to write this). Note that I assume that i < j
, but it would be trivial to extend the function to correctly handle the other cases:
swapElementsAt :: Int -> Int -> [a] -> [a]
swapElementsAt i j xs = let elemI = xs !! i
elemJ = xs !! j
left = take i xs
middle = take (j - i - 1) (drop (i + 1) xs)
right = drop (j + 1) xs
in left ++ [elemJ] ++ middle ++ [elemI] ++ right
这篇关于按索引交换列表中的两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!