Swap two elements in a list by its indices

后端 未结 9 2072
暗喜
暗喜 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:16

    This is a strange thing to do, but this should work, aside from the off-by-one errors you'll have to fix since I'm writing this on my phone. This version avoids going over the same segments of the list any more times than necessary.

    swap' :: Int -> Int -> [a] -> [a]
    swap' first second lst = beginning ++ [y] ++ middle ++ [x] ++ end
      where
        (beginning, (x : r)) = splitAt first lst
        (middle, (y : end)) = splitAt (second - first - 1) r
    
    swap x y | x == y = id
             | otherwise = swap' (min x y) (max x y)
    

提交回复
热议问题