Swap two elements in a list by its indices

后端 未结 9 2034
暗喜
暗喜 2020-12-30 08:25

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 a

9条回答
  •  爱一瞬间的悲伤
    2020-12-30 09:02

    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
    

提交回复
热议问题