swap.hs (979B)

1 import Data.Foldable (toList) 2 import Data.Sequence (Seq) 3 import qualified Data.Sequence as Seq 4 import Test.QuickCheck 5 6 swap :: Int -> [a] -> [a] 7 swap k xs = toList xsSwap 8 where 9 xsAsSeq = Seq.fromList xs 10 n = Seq.length xsAsSeq 11 xsSwap = let kth = xsAsSeq `Seq.index` k 12 nlkth = xsAsSeq `Seq.index` (n - k - 1) 13 in Seq.update (n - k - 1) kth . Seq.update k nlkth $ xsAsSeq 14 15 -- Tests ----------------------------------------------------------------------- 16 17 newtype Constrained = Constrained { getItems :: (Int, [Int]) } deriving Show 18 19 instance Arbitrary Constrained where 20 arbitrary = do 21 NonEmpty xs <- arbitrary :: Gen (NonEmptyList Int) 22 let n = length xs 23 k <- choose (0, n - 1) 24 return $ Constrained (k, xs) 25 26 prop_swapsKth :: Constrained -> Bool 27 prop_swapsKth (Constrained (k, xs)) = 28 let (swapped, n) = (swap k xs, length xs) 29 in xs !! k == swapped !! (n - k - 1) 30 && xs !! (n - k - 1) == swapped !! k 31