Swap two elements in a list by its indices

后端 未结 9 2060
暗喜
暗喜 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 08:57

    first-order one-pass swapping

    swap 1 j    l  = let (jth,ith:l') = swapHelp j l ith in jth:l'
    swap j 1    l  = swap 1 j l
    swap i j (h:t) = h : swap (i-1) (j-1) t
    
    swapHelp 1 (h:t) x = (h,x:t)
    swapHelp n (h:t) x = (y,h:t') where
                         (y,  t') = swapHelp (n-1) t x
    
    • now with precondition in compliance with original question, i.e. relaxed to 1 <= i,j <= length l for swap i j l
    • draws heavily on an idea by @dfeuer to reduce the problem to swapping the 1st element of a list with another from a given position

提交回复
热议问题