haskell - Swap two elements in a list by its indices -
is there way swap 2 elements in list if thing know elements position @ occur in list.
to more specific, looking this:
swapelementsat :: int -> int -> [int] -> [int] that behave that:
> swapelementsat 1 3 [5,4,3,2,1] -- swap first , third elements [3,4,5,2,1] i thought built-in function might exists in haskell wasn't able find it.
haskell doesn't have such function, because little bit un-functional. trying achieve?
anyway, if want it, can implement own version of (maybe there more idiomatic way write this). note assume i < j, trivial extend function correctly handle other cases:
swapelementsat :: int -> int -> [a] -> [a] swapelementsat j xs = let elemi = xs !! elemj = xs !! j left = take xs middle = take (j - - 1) (drop (i + 1) xs) right = drop (j + 1) xs in left ++ [elemj] ++ middle ++ [elemi] ++ right
Comments
Post a Comment