Swap two elements in a list by its indices

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

    That's how I solved it:

    swapElementsAt :: Int -> Int -> [a] -> [a]
    swapElementsAt a b list = list1 ++ [list !! b] ++ list2 ++ [list !! a] ++ list3
        where   list1 = take a list;
                list2 = drop (succ a) (take b list);
                list3 = drop (succ b) list
    

    Here I used the convention that position 0 is the first. My function expects a<=b.

    What I like most in my program is the line take a list.

    Edit: If you want to get more such cool lines, look at this code:

    swapElementsAt :: Int -> Int -> [a] -> [a]
    swapElementsAt a another list = list1 ++ [list !! another] ++ list2 ++ [list !! a] ++ list3
        where   list1 = take a list;
                list2 = drop (succ a) (take another list);
                list3 = drop (succ another) list
    

提交回复
热议问题