Swap two elements in a list by its indices

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

    I really like @dfeuer 's solution. However there's still room for optimization by way of deforestation:

    swap' :: Int -> Int -> [a] -> [a]
    swap' first second lst = beginning $ [y] ++ (middle $ [x] ++ end)
      where
        (beginning, (x : r)) = swapHelp first lst
        (middle, (y : end)) = swapHelp (second - first - 1) r
    
    swapHelp :: Int -> [a] -> ([a] -> [a],[a])
    swapHelp 0 l     = (    id , l)
    swapHelp n (h:t) = ((h:).f , r) where
                       (     f , r) = swapHelp (n-1) t
    

提交回复
热议问题