Swap two elements in a list by its indices

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

    For positional swapping, using a more complex fold function I have changed the value of the smalest (min) index with the value of the greates (xs!!(y-ii)) and then keep the value for the greatest index in the temp, until find it, the index(max).

    I used min and max to make sure I encounter in proper order the indices otherwise I would have to put more checks and conditions in the folds function.

    folds _ _ _ _ [] = []
    folds i z y tmp (x:xs)
        | i == z = (xs!!(y-ii)):folds ii z y x xs
        | i == y = tmp:folds ii z y 0 xs
        | otherwise = x:folds ii z y tmp xs
        where 
            ii = i+1
    
    swapElementsAt x y xs = folds 0 a b 0 xs
        where
            a = min x y
            b = max x y
    

    Results

    > swapElementsAt 0 1 [1,1,1,3,4,9]
    [1,1,1,3,4,9]
    > swapElementsAt 0 5 [1,1,1,3,4,9]
    [9,1,1,3,4,1]
    > swapElementsAt 3 1 [1,1,1,3,4,5]
    [1,3,1,1,4,5]
    > swapElementsAt 1 3 [1,1,1,3,4,5]
    [1,3,1,1,4,5]
    > swapElementsAt 5 4 [1,1,1,3,4,5]
    [1,1,1,3,5,4]
    
    

提交回复
热议问题