Swap two elements in a list by its indices

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

    There is also a recursive solution:

    setElementAt :: a -> Int -> [a] -> [a]
    setElementAt a 0 (_:tail) = a:tail
    setElementAt a pos (b:tail) = b:(setElementAt a (pred pos) tail)
    
    swapElementsAt :: Int -> Int -> [a] -> [a]
    swapElementsAt 0 b list@(c:tail) = (list !! b):(setElementAt c (pred b) tail)
    swapElementsAt a b (c:tail) = c:(swapElementsAt (pred a) (pred b) tail)
    

提交回复
热议问题