vector-algorithms 0.9.1.0 → 0.9.1.1
raw patch · 8 files changed
+898/−19 lines, 8 filesdep ~QuickCheckdep ~taggedPVP: major bump suggested
API removals or changes: PVP suggests a major version bump
Dependency ranges changed: QuickCheck, tagged
API changes (from Hackage documentation)
- Data.Vector.Algorithms: nub :: forall v e. (Vector v e, Ord e) => v e -> v e
+ Data.Vector.Algorithms: nub :: (Vector v e, Ord e) => v e -> v e
- Data.Vector.Algorithms: nubBy :: forall v e. Vector v e => Comparison e -> v e -> v e
+ Data.Vector.Algorithms: nubBy :: Vector v e => Comparison e -> v e -> v e
- Data.Vector.Algorithms: nubByMut :: forall m v e. (PrimMonad m, MVector v e) => (Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)) -> Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
+ Data.Vector.Algorithms: nubByMut :: (PrimMonad m, MVector v e) => (Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)) -> Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
Files
- CHANGELOG.md +7/−0
- src/Data/Vector/Algorithms/AmericanFlag.hs +11/−4
- src/Data/Vector/Algorithms/Radix.hs +6/−0
- tests/properties/Adversary.hs +75/−0
- tests/properties/Properties.hs +392/−2
- tests/properties/Tests.hs +238/−4
- tests/properties/Util.hs +135/−0
- vector-algorithms.cabal +34/−9
CHANGELOG.md view
@@ -1,3 +1,10 @@+## Version 0.9.1.1 (2026-11-23)++- Bump dependency upper bounds, more tests and CI improvements.+- Make Radix instances total (mainly to appease the compiler).+- AmericanFlag: Fix Lexicographic instance for pairs.+- AmericanFlag: Fix pair ordering for variable-length first components.+ ## Version 0.9.1.0 (2025-02-05) - More inlining for `sort` and `nib` functions.
src/Data/Vector/Algorithms/AmericanFlag.hs view
@@ -208,14 +208,21 @@ | otherwise = fromIntegral (B.index b i) + 1 {-# INLINE index #-} +-- | Orders pairs by their first component, then their second.+--+-- A separator bucket, below every bucket of the first component, marks+-- where the first component's key ends, so that pairs are ordered correctly+-- even when the first component's 'extent' varies, as for 'B.ByteString'. instance (Lexicographic a, Lexicographic b) => Lexicographic (a, b) where- extent (a,b) = extent a + extent b+ extent (a,b) = extent a + 1 + extent b {-# INLINE extent #-}- size _ = size (Proxy :: Proxy a) `max` size (Proxy :: Proxy b)+ size _ = (size (Proxy :: Proxy a) + 1) `max` size (Proxy :: Proxy b) {-# INLINE size #-} index i (a,b)- | i >= extent a = index i b- | otherwise = index i a+ | i < ea = 1 + index i a+ | i == ea = 0+ | otherwise = index (i - ea - 1) b+ where ea = extent a {-# INLINE index #-} instance (Lexicographic a, Lexicographic b) => Lexicographic (Either a b) where
src/Data/Vector/Algorithms/Radix.hs view
@@ -90,6 +90,7 @@ {-# INLINE size #-} radix 0 e = fromIntegral (e .&. 255) radix 1 e = fromIntegral (((e `xor` minBound) `shiftR` 8) .&. 255)+ radix _ _ = 0 {-# INLINE radix #-} instance Radix Int32 where@@ -101,6 +102,7 @@ radix 1 e = fromIntegral ((e `shiftR` 8) .&. 255) radix 2 e = fromIntegral ((e `shiftR` 16) .&. 255) radix 3 e = fromIntegral (((e `xor` minBound) `shiftR` 24) .&. 255)+ radix _ _ = 0 {-# INLINE radix #-} instance Radix Int64 where@@ -116,6 +118,7 @@ radix 5 e = fromIntegral ((e `shiftR` 40) .&. 255) radix 6 e = fromIntegral ((e `shiftR` 48) .&. 255) radix 7 e = fromIntegral (((e `xor` minBound) `shiftR` 56) .&. 255)+ radix _ _ = 0 {-# INLINE radix #-} instance Radix Word where@@ -142,6 +145,7 @@ {-# INLINE size #-} radix 0 e = fromIntegral (e .&. 255) radix 1 e = fromIntegral ((e `shiftR` 8) .&. 255)+ radix _ _ = 0 {-# INLINE radix #-} instance Radix Word32 where@@ -153,6 +157,7 @@ radix 1 e = fromIntegral ((e `shiftR` 8) .&. 255) radix 2 e = fromIntegral ((e `shiftR` 16) .&. 255) radix 3 e = fromIntegral ((e `shiftR` 24) .&. 255)+ radix _ _ = 0 {-# INLINE radix #-} instance Radix Word64 where@@ -168,6 +173,7 @@ radix 5 e = fromIntegral ((e `shiftR` 40) .&. 255) radix 6 e = fromIntegral ((e `shiftR` 48) .&. 255) radix 7 e = fromIntegral ((e `shiftR` 56) .&. 255)+ radix _ _ = 0 {-# INLINE radix #-} instance (Radix i, Radix j) => Radix (i, j) where
+ tests/properties/Adversary.hs view
@@ -0,0 +1,75 @@+{-# LANGUAGE RankNTypes #-}+-- The comparison functions in this module have side effects (hidden behind+-- unsafePerformIO), so stop GHC from sharing or floating their calls.+{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}++-- | Worst-case inputs for quicksort-based algorithms, built with McIlroy's+-- adversary ("A Killer Adversary for Quicksort", Software: Practice and+-- Experience, 1999), and a way of counting comparisons.+--+-- The adversary runs the algorithm on a vector of item ids with a comparison+-- that decides item values lazily. Items start as "gas" (larger than any+-- decided value), and whenever two gas items are compared, one of them is+-- frozen to the next smallest value, choosing the one that looks like the+-- current pivot candidate. This makes every partition as unbalanced as+-- possible. Since the algorithm is deterministic, rerunning it on the values+-- the adversary decided reproduces exactly the same worst-case behaviour.+module Adversary+ ( CmpAlgo+ , killerInput+ , countComparisons+ ) where++import Control.Monad+import Control.Monad.ST (ST, stToIO)+import Data.IORef+import System.IO.Unsafe (unsafePerformIO)++import qualified Data.Vector as V+import qualified Data.Vector.Mutable as MV++-- | An in-place algorithm parameterised by its comparison.+type CmpAlgo = forall s. (Int -> Int -> Ordering) -> MV.MVector s Int -> ST s ()++-- | An input of length @n@ that drives the given algorithm into its worst+-- case, as far as McIlroy's adversary can find one.+killerInput :: CmpAlgo -> Int -> V.Vector Int+killerInput algo n = unsafePerformIO $ do+ vals <- MV.replicate n gas+ nsolid <- newIORef 0+ candidate <- newIORef 0+ let freeze z = do s <- readIORef nsolid+ MV.write vals z s+ writeIORef nsolid (s + 1)+ cmpIO x y = do+ vx <- MV.read vals x+ vy <- MV.read vals y+ when (vx == gas && vy == gas) $ do+ c <- readIORef candidate+ freeze (if x == c then x else y)+ vx' <- MV.read vals x+ vy' <- MV.read vals y+ if vx' == gas+ then writeIORef candidate x+ else when (vy' == gas) $ writeIORef candidate y+ pure $! compare vx' vy'+ cmp x y = unsafePerformIO (cmpIO x y)+ {-# NOINLINE cmp #-}+ stToIO $ V.thaw (V.enumFromN 0 n) >>= algo cmp+ V.freeze vals+ where+ gas = n++-- | Run the algorithm on a copy of the input, returning the number of+-- comparisons it made and the resulting vector.+countComparisons :: CmpAlgo -> V.Vector Int -> (Int, V.Vector Int)+countComparisons algo v = unsafePerformIO $ do+ count <- newIORef (0 :: Int)+ let cmp x y = unsafePerformIO $ do modifyIORef' count (+ 1)+ pure $! compare x y+ {-# NOINLINE cmp #-}+ r <- stToIO $ do mv <- V.thaw v+ algo cmp mv+ V.freeze mv+ c <- readIORef count+ pure (c, r)
tests/properties/Properties.hs view
@@ -9,6 +9,8 @@ import Optimal +import Adversary+ import Control.Monad import Control.Monad.ST @@ -25,6 +27,9 @@ import qualified Data.Vector.Generic.Mutable as G import qualified Data.Vector.Generic as GV+import qualified Data.Vector.Primitive as PV+import qualified Data.Vector.Storable as SV+import qualified Data.Vector.Unboxed as UV import Data.Vector.Algorithms.Optimal (Comparison) import Data.Vector.Algorithms.Radix (radix, passes, size)@@ -103,8 +108,8 @@ vtail = V.drop k newVec prop_sorted vhead .&&.- -- Every element in the head should be < every element in the tail.- if V.null vtail then 1 == 1 else V.maximum vhead <= V.minimum vtail+ -- Every element in the head should be <= every element in the tail.+ (V.null vhead || V.null vtail || V.maximum vhead <= V.minimum vtail) prop_sized_empty :: (Ord e) => (forall s. MV.MVector s e -> Int -> ST s ()) -> Property prop_sized_empty algo = prop_empty (flip algo 0) .&&. prop_empty (flip algo 10)@@ -222,3 +227,388 @@ prop_nub :: (Ord e, Show e) => Vector e -> Property prop_nub v = V.fromList (nub (V.toList v)) === Alg.nub v++-- | Sorting a large structured vector gives the same result as+-- 'Data.List.sort'. This checks both sortedness and that the output is a+-- permutation of the input, in time linear in the vector length.+prop_large_sort :: (forall s mv. G.MVector mv Int => mv s Int -> ST s ())+ -> LargeVec -> Property+prop_large_sort algo (LargeVec _ v) =+ modify algo v === V.fromList (sort (V.toList v))++-- | Sorting a large structured vector of (key, original index) pairs by key+-- gives the same result as the stable 'Data.List.sortBy'. This also checks+-- stability.+prop_large_stable :: (forall e s mv. G.MVector mv e => Comparison e -> mv s e -> ST s ())+ -> LargeVec -> Property+prop_large_stable algo (LargeVec _ v) =+ modify (algo (comparing fst)) kv === V.fromList (sortBy (comparing fst) (V.toList kv))+ where+ kv = V.imap (\i k -> (k, i)) v++-- | 'sortUniq' on a large structured vector gives the sorted distinct+-- elements.+prop_large_sortUniq :: (forall s . MV.MVector s Int -> ST s (Vector Int))+ -> LargeVec -> Property+prop_large_sortUniq algo (LargeVec _ v) = runST $ do+ mv <- V.thaw v+ v' <- algo mv+ pure (v' === V.fromList (M.keys (toBag v)))++-- ---------------------------------------------------------------------------+-- Properties of the @...ByBounds@ functions++-- | The elements of the result outside [l, u) are unchanged from the input.+outsideUnchanged :: Vector Int -> Int -> Int -> Vector Int -> Property+outsideUnchanged v l u r =+ counterexample "elements outside [l, u) changed" $+ V.take l r == V.take l v && V.drop u r == V.drop u v++sliceList :: Int -> Int -> Vector e -> [e]+sliceList l u = V.toList . V.slice l (u - l)++prop_sortByBounds :: (forall s. MV.MVector s Int -> Int -> Int -> ST s ())+ -> BoundsCase -> Property+prop_sortByBounds algo (BoundsCase v l u _) =+ outsideUnchanged v l u r .&&. sliceList l u r === sort (sliceList l u v)+ where+ r = modify (\a -> algo a l u) v++-- | [l, l+k) holds the k smallest elements of the input's [l, u), and+-- [l+k, u) holds the rest.+prop_selectByBounds :: (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())+ -> BoundsCase -> Property+prop_selectByBounds algo (BoundsCase v l u k) =+ outsideUnchanged v l u r+ .&&. sort (sliceList l (l + k) r) === lo+ .&&. sort (sliceList (l + k) u r) === hi+ where+ r = modify (\a -> algo a k l u) v+ (lo, hi) = splitAt k (sort (sliceList l u v))++-- | [l, l+k) holds the k smallest elements of the input's [l, u) in order,+-- and [l+k, u) holds the rest.+prop_partialSortByBounds :: (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())+ -> BoundsCase -> Property+prop_partialSortByBounds algo (BoundsCase v l u k) =+ outsideUnchanged v l u r+ .&&. sliceList l (l + k) r === lo+ .&&. sort (sliceList (l + k) u r) === hi+ where+ r = modify (\a -> algo a k l u) v+ (lo, hi) = splitAt k (sort (sliceList l u v))++-- ---------------------------------------------------------------------------+-- Properties of the heap operations exported by Data.Vector.Algorithms.Heap.+-- The heap is a 4-ary max-heap: the children of index i are 4i+1 .. 4i+4.++isHeap :: [Int] -> Bool+isHeap xs = and [ h V.! ((i - 1) `div` 4) >= h V.! i | i <- [1 .. V.length h - 1] ]+ where h = V.fromList xs++heapProp :: [Int] -> Property+heapProp xs = counterexample ("not a heap: " ++ show xs) (isHeap xs)++type HeapifyAlgo = forall s. MV.MVector s Int -> Int -> Int -> ST s ()++-- | 'heapify' makes [l, u) a heap, without changing its elements or anything+-- outside it.+prop_heapify :: HeapifyAlgo -> BoundsCase -> Property+prop_heapify heapify (BoundsCase v l u _) =+ outsideUnchanged v l u r+ .&&. heapProp (sliceList l u r)+ .&&. sort (sliceList l u r) === sort (sliceList l u v)+ where+ r = modify (\a -> heapify a l u) v++-- | Given a heap in [l, u), 'popTo' to an index t outside [l, u) moves the+-- maximum to t and leaves a heap of the remaining elements plus the old+-- value at t in [l, u).+prop_popTo :: HeapifyAlgo+ -> (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())+ -> BoundsCase -> Property+prop_popTo heapify popTo (BoundsCase v l u _) =+ u > l && u < V.length v ==>+ forAll (choose (u, V.length v - 1)) $ \t ->+ let h = modify (\a -> heapify a l u) v+ r = modify (\a -> popTo a l u t) h+ old = sliceList l u h+ in r V.! t === maximum old+ .&&. heapProp (sliceList l u r)+ .&&. sort (sliceList l u r) === sort (delete (maximum old) old ++ [h V.! t])+ .&&. counterexample "elements outside [l, u) and t changed"+ (V.toList (V.take l r) == V.toList (V.take l h)+ && and [ r V.! i == h V.! i | i <- [u .. V.length v - 1], i /= t ])++-- | Given a heap in [l, u), 'pop' with upper bound u-1 moves the maximum to+-- u-1 and leaves a heap in [l, u-1).+prop_pop :: HeapifyAlgo+ -> (forall s. MV.MVector s Int -> Int -> Int -> ST s ())+ -> BoundsCase -> Property+prop_pop heapify pop (BoundsCase v l u _) =+ u - l >= 1 ==>+ outsideUnchanged v l u r+ .&&. r V.! (u - 1) === maximum (sliceList l u v)+ .&&. heapProp (sliceList l (u - 1) r)+ .&&. sort (sliceList l u r) === sort (sliceList l u v)+ where+ r = modify (\a -> heapify a l u >> pop a l (u - 1)) v++-- | Given a heap in [l, u), 'sortHeap' with l <= m < u puts the largest+-- u-m elements, sorted, into [m, u).+prop_sortHeap :: HeapifyAlgo+ -> (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())+ -> BoundsCase -> Property+prop_sortHeap heapify sortHeap (BoundsCase v l u k) =+ u > l ==>+ let m = min (l + k) (u - 1)+ r = modify (\a -> heapify a l u >> sortHeap a l m u) v+ sorted = sort (sliceList l u v)+ in outsideUnchanged v l u r+ .&&. sliceList m u r === drop (m - l) sorted+ .&&. sort (sliceList l u r) === sorted++-- | Building a heap by repeated 'heapInsert' gives a heap of the inserted+-- elements.+prop_heapInsert :: (forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s ())+ -> LargeVec -> Property+prop_heapInsert heapInsert (LargeVec _ v) =+ heapProp (V.toList r) .&&. sort (V.toList r) === sort (V.toList v)+ where+ r = runST $ do+ a <- MV.new (V.length v)+ V.imapM_ (\i e -> heapInsert a 0 i e) v+ V.freeze a++-- ---------------------------------------------------------------------------+-- Worst-case inputs for introsort++-- | On an input built by McIlroy's adversary for this algorithm, the result+-- is correct and the number of comparisons stays within 6 n lg n.+--+-- Without introsort's heap sort fallback these inputs need about n^2/4+-- comparisons, which exceeds the bound for every n >= 500 tested here, so+-- this checks that the fallback works. With it, the observed count is at+-- most about 3.9 n lg n.+prop_killer :: CmpAlgo -> (Vector Int -> Vector Int -> Property) -> Property+prop_killer algo correct = forAll (choose (500, 5000)) $ \n ->+ let input = killerInput algo n+ (c, r) = countComparisons algo input+ bound = 6 * fromIntegral n * logBase 2 (fromIntegral n) :: Double+ in correct input r+ .&&. counterexample ("n = " ++ show n ++ ": " ++ show c+ ++ " comparisons exceeds 6 n lg n = " ++ show (round bound :: Int))+ (fromIntegral c <= bound)++-- | The result is the sorted input.+resultSorted :: Vector Int -> Vector Int -> Property+resultSorted input r = r === V.fromList (sort (V.toList input))++-- | The first half of the result holds the smallest half of the input, in+-- order if @ordered@ is set.+resultHalf :: Bool -> Vector Int -> Vector Int -> Property+resultHalf ordered input r =+ (if ordered then front else sort front) === lo .&&. sort back === hi+ where+ k = V.length input `div` 2+ (front, back) = splitAt k (V.toList r)+ (lo, hi) = splitAt k (sort (V.toList input))++-- ---------------------------------------------------------------------------+-- Sorting large vectors of other element types++-- | Like 'prop_large_sort', but first maps the 'Int' keys to another element+-- type. Mapping with a function that has few distinct values in its first+-- component gives large groups of elements that only differ later on.+prop_large_sort_via :: (Ord e, Show e)+ => (Int -> e)+ -> (forall s mv. G.MVector mv e => mv s e -> ST s ())+ -> LargeVec -> Property+prop_large_sort_via f algo (LargeVec _ v) =+ modify algo w === V.fromList (sort (V.toList w))+ where+ w = V.map f v++-- ---------------------------------------------------------------------------+-- Searching++type PSearchBounds = forall s. (Int -> Bool) -> MV.MVector s Int -> Int -> Int -> ST s Int+type CmpSearchBounds = forall s. MV.MVector s Int -> Int -> Int -> Int -> ST s Int++runSearch :: Vector Int -> (forall s. MV.MVector s Int -> ST s Int) -> Int+runSearch v search = runST (V.thaw v >>= search)++-- | The index in [l, u] at which a monotone predicate turns from False to+-- True on the sorted range [l, u), or u if it is False throughout.+modelP :: (Int -> Bool) -> Vector Int -> Int -> Int -> Int+modelP p v l u = l + length (takeWhile (not . p) (sliceList l u v))++-- | A predicate search over [l, u) agrees with the model, for the monotone+-- predicates (>= e) and (> e).+prop_searchPBounds :: PSearchBounds -> SearchCase -> Property+prop_searchPBounds search (SearchCase v l u e) = conjoin+ [ counterexample name $ runSearch v (\a -> search p a l u) === modelP p v l u+ | (name, p) <- [(">= e", (>= e)), ("> e", (> e))] ]++-- | A predicate search over the whole vector agrees with the model.+prop_searchP :: (forall s. (Int -> Bool) -> MV.MVector s Int -> ST s Int)+ -> SearchCase -> Property+prop_searchP search (SearchCase v _ _ e) = conjoin+ [ counterexample name $ runSearch v (search p) === modelP p v 0 (V.length v)+ | (name, p) <- [(">= e", (>= e)), ("> e", (> e))] ]++-- | 'binarySearchLByBounds' finds the first index in [l, u] at which e can be+-- inserted, and 'binarySearchRByBounds' the last.+prop_searchLBounds, prop_searchRBounds :: CmpSearchBounds -> SearchCase -> Property+prop_searchLBounds search (SearchCase v l u e) =+ runSearch v (\a -> search a e l u) === modelP (>= e) v l u+prop_searchRBounds search (SearchCase v l u e) =+ runSearch v (\a -> search a e l u) === modelP (> e) v l u++-- | 'binarySearchByBounds' finds some index in [l, u] at which e can be+-- inserted while keeping [l, u) sorted.+prop_searchAnyBounds :: CmpSearchBounds -> SearchCase -> Property+prop_searchAnyBounds search (SearchCase v l u e) =+ counterexample ("result " ++ show i) $+ modelP (>= e) v l u <= i && i <= modelP (> e) v l u+ where+ i = runSearch v (\a -> search a e l u)++-- ---------------------------------------------------------------------------+-- Optimal sorts at arbitrary indices++-- | A @sortNByIndex@ function from "Data.Vector.Algorithms.Optimal", taking+-- its n indices as a list.+type ByIndexAlgo = forall s. [Int] -> MV.MVector s (Int, Int) -> ST s ()++-- | Placing n elements at distinct positions of a larger vector, given in+-- any order, and sorting them by index: read back in the order of the+-- indices, the elements are stably sorted (by their first component), and+-- every other position is unchanged. This is checked for every permutation+-- of n distinct keys and every input in the exhaustive stability set.+prop_optimal_byIndex :: Int -> ByIndexAlgo -> Property+prop_optimal_byIndex n algo =+ forAll (choose (n, 20)) $ \len ->+ forAll (take n <$> shuffle [0 .. len - 1]) $ \ixs ->+ conjoin [ check len ixs (V.toList xs) | xs <- inputs ]+ where+ inputs :: [Vector (Int, Int)]+ inputs = map (\p -> V.fromList (zip p [0 ..])) (permutations [0 .. n - 1])+ ++ stability n+ check len ixs xs =+ let filler = V.generate len (\i -> (-1, -1 - i))+ before = filler V.// zip ixs xs+ after = modify (algo ixs) before+ others = [ i | i <- [0 .. len - 1], i `notElem` ixs ]+ in counterexample ("indices " ++ show ixs ++ ", input " ++ show xs) $+ map (after V.!) ixs === sortBy (comparing fst) xs+ .&&. counterexample "positions outside the indices changed"+ (map (after V.!) others == map (before V.!) others)++-- ---------------------------------------------------------------------------+-- nub++type SortUniqBy = forall s. Comparison Int -> MV.MVector s Int -> ST s (MV.MVector s Int)++-- | The first element of each equivalence class, in the order of the input,+-- for a comparison that is 'compare' on the given key.+firstOccurrencesOn :: (Int -> Int) -> [Int] -> [Int]+firstOccurrencesOn key = go M.empty+ where+ go _ [] = []+ go seen (x:xs)+ | M.member (key x) seen = go seen xs+ | otherwise = x : go (M.insert (key x) () seen) xs++-- | The comparisons nub is tested with, as a name, the comparison, and the+-- key it compares on (the descending comparison has the same classes as+-- 'compare').+nubComparisons :: [(String, Comparison Int, Int -> Int)]+nubComparisons =+ [ ("compare", compare, id)+ , ("descending", flip compare, id)+ , ("modulo 7", comparing (`mod` 7), (`mod` 7))+ , ("absolute", comparing abs, abs)+ ]++-- | 'Alg.nubByMut' with the given sortUniqBy keeps the first element of each+-- equivalence class in input order, and leaves its input unchanged.+prop_nubByMut :: SortUniqBy -> Vector Int -> Property+prop_nubByMut alg v = conjoin+ [ counterexample name $+ let (r, v') = runST $ do+ mv <- V.thaw v+ d <- Alg.nubByMut alg cmp mv+ (,) <$> V.freeze d <*> V.freeze mv+ in V.toList r === firstOccurrencesOn key (V.toList v)+ .&&. counterexample "input changed" (v' == v)+ | (name, cmp, key) <- nubComparisons ]++-- | 'Alg.nubBy' keeps the first element of each equivalence class in input+-- order.+prop_nubBy :: Vector Int -> Property+prop_nubBy v = conjoin+ [ counterexample name $+ V.toList (Alg.nubBy cmp v) === firstOccurrencesOn key (V.toList v)+ | (name, cmp, key) <- nubComparisons ]++-- ---------------------------------------------------------------------------+-- Other vector types+--+-- The algorithms are INLINE and get specialised to each vector type, so+-- also run them on unboxed, storable and primitive vectors, not just the+-- boxed vectors used everywhere else.++type GenAlgo = forall s mv. G.MVector mv Int => mv s Int -> ST s ()+type GenUniqAlgo = forall s mv. G.MVector mv Int => mv s Int -> ST s (mv s Int)++-- | Run an in-place algorithm on the input converted to each of the other+-- vector types, and check each result with the given property.+prop_vector_types :: GenAlgo -> (Vector Int -> Vector Int -> Property)+ -> Vector Int -> Property+prop_vector_types algo correct v = conjoin+ [ counterexample "unboxed" $ correct v (via (undefined :: UV.Vector Int))+ , counterexample "storable" $ correct v (via (undefined :: SV.Vector Int))+ , counterexample "primitive" $ correct v (via (undefined :: PV.Vector Int))+ ]+ where+ via :: GV.Vector w Int => w Int -> Vector Int+ via proxy = GV.convert (GV.modify algo (GV.convert v `asTypeOf` proxy))++-- | 'prop_vector_types' for algorithms returning a vector of unique+-- elements: the result is the sorted distinct elements of the input.+prop_vector_types_uniq :: GenUniqAlgo -> Vector Int -> Property+prop_vector_types_uniq algo v = conjoin+ [ counterexample "unboxed" $ via (undefined :: UV.Vector Int) === expected+ , counterexample "storable" $ via (undefined :: SV.Vector Int) === expected+ , counterexample "primitive" $ via (undefined :: PV.Vector Int) === expected+ ]+ where+ expected = M.keys (toBag v)+ via :: GV.Vector w Int => w Int -> [Int]+ via proxy = runST $ do+ mv <- GV.thaw (GV.convert v `asTypeOf` proxy)+ r <- algo mv+ GV.toList . (`asTypeOf` proxy) <$> GV.freeze r++-- | A stable sort is stable on unboxed vectors of (key, original index)+-- pairs.+prop_stable_unboxed :: (forall s mv. G.MVector mv (Int, Int)+ => Comparison (Int, Int) -> mv s (Int, Int) -> ST s ())+ -> LargeVec -> Property+prop_stable_unboxed algo (LargeVec _ v) =+ UV.toList (GV.modify (algo (comparing fst)) kv)+ === sortBy (comparing fst) (UV.toList kv)+ where+ kv = UV.imap (\i k -> (k, i)) (UV.convert v)++-- | 'Alg.nub' on each of the other vector types keeps the first occurrence+-- of each element, in input order.+prop_nub_vector_types :: Vector Int -> Property+prop_nub_vector_types v = conjoin+ [ counterexample "unboxed" $ UV.toList (Alg.nub (UV.convert v)) === expected+ , counterexample "storable" $ SV.toList (Alg.nub (SV.convert v)) === expected+ , counterexample "primitive" $ PV.toList (Alg.nub (PV.convert v)) === expected+ ]+ where+ expected = firstOccurrencesOn id (V.toList v)
tests/properties/Tests.hs view
@@ -4,15 +4,23 @@ import Properties +import Adversary (CmpAlgo)+ import Util -import Test.QuickCheck+import Test.QuickCheck hiding (quickCheck, quickCheckWith)+import qualified Test.QuickCheck as QC +import Data.IORef+import System.Exit (exitFailure)+import System.IO.Unsafe (unsafePerformIO)+ import Control.Monad import Control.Monad.ST import Data.Int import Data.Word+import Data.Ord (Down (..), comparing) import qualified Data.ByteString as B @@ -70,6 +78,7 @@ , ("merge sortUniq", MonoAlgo (runFreeze M.sortUniq)) , ("heap_sortUniq", MonoAlgo (runFreeze H.sortUniq)) , ("tim_sortUniq", MonoAlgo (runFreeze T.sortUniq))+ , ("flag_sortUniq", MonoAlgo (runFreeze AF.sortUniq)) ] check_Int_partialsort = forM_ algos $ \(name,algo) ->@@ -88,9 +97,179 @@ , ("heap select", WrapSizeAlgo H.select) ] -check_nub = quickCheckWith args (label "nub Int" . (prop_nub @Int))+check_large = do+ forM_ sorts $ \(name, algo) ->+ qc (label name . prop_large_sort (unWrapAlgo algo))+ qc (label "merge sort stable" . prop_large_stable M.sortBy)+ qc (label "timsort stable" . prop_large_stable T.sortBy)+ forM_ uniqs $ \(name, algo) ->+ qc (label name . prop_large_sortUniq (unWrapMonoAlgo algo))+ where+ qc = quickCheckWith args { maxSuccess = 300 }+ sorts :: [(String, WrappedAlgo Int ())]+ sorts = [ ("introsort", WrapAlgo INT.sort)+ , ("merge sort", WrapAlgo M.sort)+ , ("heapsort", WrapAlgo H.sort)+ , ("timsort", WrapAlgo T.sort)+ , ("radix sort", WrapAlgo R.sort)+ , ("american flag sort", WrapAlgo AF.sort)+ ]+ uniqs :: [(String, WrappedMonoAlgo Int (Vector Int))]+ uniqs = [ ("intro sortUniq", MonoAlgo (runFreeze INT.sortUniq))+ , ("merge sortUniq", MonoAlgo (runFreeze M.sortUniq))+ , ("heap sortUniq", MonoAlgo (runFreeze H.sortUniq))+ , ("tim sortUniq", MonoAlgo (runFreeze T.sortUniq))+ , ("flag sortUniq", MonoAlgo (runFreeze AF.sortUniq))+ ] +check_bounds = do+ qc (label "intro sortByBounds" . prop_sortByBounds (INT.sortByBounds compare))+ qc (label "heap sortByBounds" . prop_sortByBounds (H.sortByBounds compare))+ qc (label "insertion sortByBounds" . prop_sortByBounds (INS.sortByBounds compare))+ qc (label "intro selectByBounds" . prop_selectByBounds (INT.selectByBounds compare))+ qc (label "heap selectByBounds" . prop_selectByBounds (H.selectByBounds compare))+ qc (label "intro partialSortByBounds" . prop_partialSortByBounds (INT.partialSortByBounds compare))+ qc (label "heap partialSortByBounds" . prop_partialSortByBounds (H.partialSortByBounds compare))+ where+ qc = quickCheckWith args { maxSuccess = 500 } +check_heap_ops = do+ qc (label "heapify" . prop_heapify heapify)+ qc (label "pop" . prop_pop heapify (H.pop compare))+ qc (label "popTo" . prop_popTo heapify (H.popTo compare))+ qc (label "sortHeap" . prop_sortHeap heapify (H.sortHeap compare))+ qc (label "heapInsert" . prop_heapInsert (H.heapInsert compare))+ where+ qc :: Testable prop => prop -> IO ()+ qc = quickCheckWith args { maxSuccess = 500 }+ heapify :: HeapifyAlgo+ heapify = H.heapify compare++check_killer = do+ qc "intro sort" (\cmp a -> INT.sortBy cmp a) resultSorted+ qc "intro select" (\cmp a -> INT.selectBy cmp a (half a)) (resultHalf False)+ qc "intro partial sort" (\cmp a -> INT.partialSortBy cmp a (half a)) (resultHalf True)+ where+ qc :: String -> CmpAlgo -> (Vector Int -> Vector Int -> Property) -> IO ()+ qc name algo correct = quickCheckWith args { maxSuccess = 50 } (label name (prop_killer algo correct))+ half a = MV.length a `div` 2++check_flag_compound = do+ -- Few distinct first components, so that large groups of elements are+ -- distinguished only by their second component.+ qc "flag (Word8, Word8)" $ prop_large_sort_via (\x -> (w8 (x `mod` 3), w8 x)) AF.sort+ qc "flag (Word16, Word16)" $ prop_large_sort_via (\x -> (w16 (x `mod` 3), w16 x)) AF.sort+ qc "flag (Int, Int)" $ prop_large_sort_via (\x -> (x `mod` 3, x)) AF.sort+ qc "flag (Word8, Int)" $ prop_large_sort_via (\x -> (w8 (x `mod` 3), x)) AF.sort+ qc "flag (Int, Word8)" $ prop_large_sort_via (\x -> (x `mod` 3, w8 x)) AF.sort+ qc "flag Either" $ prop_large_sort_via+ (\x -> if even x then Left (w16 (x `div` 7)) else Right x) AF.sort+ qc "flag (ByteString, Int)" $ prop_large_sort_via+ (\x -> (B.pack [fromIntegral (x `mod` 3)], x)) AF.sort+ -- First components of varying length, sharing prefixes, so that one+ -- element's first component can end where another's continues.+ qc "flag (variable ByteString, Int)" $ prop_large_sort_via (\x -> (varBytes x, x)) AF.sort+ qc "flag ((Int, variable ByteString), Int)" $+ prop_large_sort_via (\x -> ((x `mod` 2, varBytes x), x)) AF.sort+ -- A custom radix and comparison that sort into descending order.+ qc "flag sortBy descending" $ prop_large_sort_via (Down . w32)+ (AF.sortBy compare (\(Down e) i -> AF.terminate e i) 256+ (\i (Down e) -> 255 - AF.index i e))+ where+ qc :: Testable prop => String -> prop -> IO ()+ qc name = quickCheckWith args { maxSuccess = 300 } . label name+ w8 :: Int -> Word8+ w8 = fromIntegral+ w16 :: Int -> Word16+ w16 = fromIntegral+ w32 :: Int -> Word32+ w32 = fromIntegral+ -- 0 to 3 bytes, drawn from few values (including 0 and 255).+ varBytes :: Int -> B.ByteString+ varBytes x = B.pack . take (x `mod` 4) $+ map (\d -> [0, 1, 97, 255] !! ((x `div` d) `mod` 4)) [4, 16, 64]++check_search = do+ qc "binarySearchPBounds" $ prop_searchPBounds SR.binarySearchPBounds+ qc "gallopingSearchLeftPBounds" $ prop_searchPBounds SR.gallopingSearchLeftPBounds+ qc "gallopingSearchRightPBounds" $ prop_searchPBounds SR.gallopingSearchRightPBounds+ qc "binarySearchP" $ prop_searchP SR.binarySearchP+ qc "gallopingSearchLeftP" $ prop_searchP SR.gallopingSearchLeftP+ qc "gallopingSearchRightP" $ prop_searchP SR.gallopingSearchRightP+ qc "binarySearchLByBounds" $ prop_searchLBounds (SR.binarySearchLByBounds compare)+ qc "binarySearchRByBounds" $ prop_searchRBounds (SR.binarySearchRByBounds compare)+ qc "binarySearchByBounds" $ prop_searchAnyBounds (SR.binarySearchByBounds compare)+ where+ qc :: Testable prop => String -> prop -> IO ()+ qc name = quickCheckWith args { maxSuccess = 1000 } . label name++check_vector_types = do+ forM_ sorts $ \(name, algo) -> do+ qc name (prop_vector_types (unWrapAlgo algo) resultSorted)+ qc (name ++ " large") (\(LargeVec _ v) -> prop_vector_types (unWrapAlgo algo) resultSorted v)+ -- Insertion sort is quadratic, so only test it on small vectors.+ qc "insertion sort" (prop_vector_types INS.sort resultSorted)+ forM_ uniqs $ \(name, algo) -> do+ qc name (prop_vector_types_uniq (unWrapUniq algo))+ qc (name ++ " large") (\(LargeVec _ v) -> prop_vector_types_uniq (unWrapUniq algo) v)+ qc "insertion sortUniq" (prop_vector_types_uniq INS.sortUniq)+ forM_ halves $ \(name, ordered, algo) ->+ qc (name ++ " large")+ (\(LargeVec _ v) -> prop_vector_types (\a -> unWrapSizeAlgo algo a (half a)) (resultHalf ordered) v)+ qc "merge sort stable unboxed" (prop_stable_unboxed M.sortBy)+ qc "timsort stable unboxed" (prop_stable_unboxed T.sortBy)+ qc "nub" prop_nub_vector_types+ qc "nub large" (\(LargeVec _ v) -> prop_nub_vector_types v)+ where+ qc :: Testable prop => String -> prop -> IO ()+ qc name = quickCheckWith args { maxSuccess = 200 } . label name+ half a = MV.length a `div` 2+ sorts :: [(String, WrappedAlgo Int ())]+ sorts = [ ("introsort", WrapAlgo INT.sort)+ , ("merge sort", WrapAlgo M.sort)+ , ("heapsort", WrapAlgo H.sort)+ , ("timsort", WrapAlgo T.sort)+ , ("radix sort", WrapAlgo R.sort)+ , ("american flag sort", WrapAlgo AF.sort)+ ]+ uniqs :: [(String, WrappedUniq)]+ uniqs = [ ("intro sortUniq", WrapUniq INT.sortUniq)+ , ("merge sortUniq", WrapUniq M.sortUniq)+ , ("heap sortUniq", WrapUniq H.sortUniq)+ , ("tim sortUniq", WrapUniq T.sortUniq)+ , ("flag sortUniq", WrapUniq AF.sortUniq)+ ]+ halves :: [(String, Bool, WrappedSizeAlgo Int ())]+ halves = [ ("intro select", False, WrapSizeAlgo INT.select)+ , ("heap select", False, WrapSizeAlgo H.select)+ , ("intro partialSort", True, WrapSizeAlgo INT.partialSort)+ , ("heap partialSort", True, WrapSizeAlgo H.partialSort)+ ]++newtype WrappedUniq = WrapUniq { unWrapUniq :: GenUniqAlgo }++check_nub = do+ quickCheckWith args (label "nub Int" . (prop_nub @Int))+ qc "nubBy" prop_nubBy+ qc "nubBy large" (\(LargeVec _ v) -> prop_nubBy v)+ forM_ sortUniqs $ \(name, alg) -> do+ qc ("nubByMut " ++ name) (prop_nubByMut (unWrapSortUniqBy alg))+ qc ("nubByMut " ++ name ++ " large") (\(LargeVec _ v) -> prop_nubByMut (unWrapSortUniqBy alg) v)+ -- Insertion sort is quadratic, so only test it on small vectors.+ qc "nubByMut insertion" (prop_nubByMut INS.sortUniqBy)+ where+ qc :: Testable prop => String -> prop -> IO ()+ qc name = quickCheckWith args { maxSuccess = 300 } . label name+ sortUniqs :: [(String, WrappedSortUniqBy)]+ sortUniqs = [ ("intro", WrapSortUniqBy INT.sortUniqBy)+ , ("merge", WrapSortUniqBy M.sortUniqBy)+ , ("heap", WrapSortUniqBy H.sortUniqBy)+ , ("tim", WrapSortUniqBy T.sortUniqBy)+ ]++newtype WrappedSortUniqBy = WrapSortUniqBy { unWrapSortUniqBy :: SortUniqBy }++ check_radix_sorts = do qc (label "radix Word8" . prop_fullsort (R.sort :: Algo Word8 ())) qc (label "radix Word16" . prop_fullsort (R.sort :: Algo Word16 ()))@@ -126,7 +305,8 @@ i2w = fromIntegral -} -check_stable = do quickCheckWith args (label "merge sort" . prop_stable M.sortBy)+check_stable = do quickCheckWith args (label "insertion sort" . prop_stable INS.sortBy)+ quickCheckWith args (label "merge sort" . prop_stable M.sortBy) quickCheckWith args (label "radix sort" . prop_stable_radix R.sortBy) quickCheckWith args (label "tim sort" . prop_stable T.sortBy) @@ -134,10 +314,23 @@ check_optimal = do qc . label "size 2" $ prop_optimal 2 O.sort2ByOffset qc . label "size 3" $ prop_optimal 3 O.sort3ByOffset qc . label "size 4" $ prop_optimal 4 O.sort4ByOffset+ qcIx . label "size 2 by index" $ prop_optimal_byIndex 2 sort2+ qcIx . label "size 3 by index" $ prop_optimal_byIndex 3 sort3+ qcIx . label "size 4 by index" $ prop_optimal_byIndex 4 sort4 where qc = quickCheck+ qcIx :: Property -> IO ()+ qcIx = quickCheckWith args { maxSuccess = 500 }+ sort2, sort3, sort4 :: ByIndexAlgo+ sort2 ixs a = case ixs of [i, j] -> O.sort2ByIndex (comparing fst) a i j+ _ -> error "sort2: expected 2 indices"+ sort3 ixs a = case ixs of [i, j, k] -> O.sort3ByIndex (comparing fst) a i j k+ _ -> error "sort3: expected 3 indices"+ sort4 ixs a = case ixs of [i, j, k, l] -> O.sort4ByIndex (comparing fst) a i j k l+ _ -> error "sort4: expected 4 indices" check_permutation = do+ qc $ label "insertion" . prop_permutation (INS.sort :: Algo Int ()) qc $ label "introsort" . prop_permutation (INT.sort :: Algo Int ()) qc $ label "heapsort" . prop_permutation (H.sort :: Algo Int ()) @@ -153,6 +346,7 @@ qc $ label "radix W32" . prop_permutation (R.sort :: Algo Word32 ()) qc $ label "radix W64" . prop_permutation (R.sort :: Algo Word64 ()) qc $ label "radix Word" . prop_permutation (R.sort :: Algo Word ())+ qc $ label "radix (Int, Int)" . prop_permutation (R.sort :: Algo (Int, Int) ()) qc $ label "flag I8" . prop_permutation (AF.sort :: Algo Int8 ()) qc $ label "flag I16" . prop_permutation (AF.sort :: Algo Int16 ()) qc $ label "flag I32" . prop_permutation (AF.sort :: Algo Int32 ())@@ -177,6 +371,7 @@ qc prop = quickCheckWith args prop check_corners = do+ qc "insertion empty" $ prop_empty (INS.sort :: Algo Int ()) qc "introsort empty" $ prop_empty (INT.sort :: Algo Int ()) qc "intropartial empty" $ prop_sized_empty (INT.partialSort :: SizeAlgo Int ()) qc "introselect empty" $ prop_sized_empty (INT.select :: SizeAlgo Int ())@@ -207,7 +402,32 @@ where qc prop = quickCheckWith args prop -main = do putStrLn "Int tests:"+-- | The number of properties that have failed so far.+failures :: IORef Int+failures = unsafePerformIO (newIORef 0)+{-# NOINLINE failures #-}++-- | Like 'QC.quickCheckWith', but records failures so that the test suite+-- can exit with a failure status.+quickCheckWith :: Testable prop => Args -> prop -> IO ()+quickCheckWith a p = do+ r <- QC.quickCheckWithResult a p+ unless (isSuccess r) $ modifyIORef' failures (+ 1)++quickCheck :: Testable prop => prop -> IO ()+quickCheck = quickCheckWith stdArgs++main :: IO ()+main = do+ runTests+ n <- readIORef failures+ when (n > 0) $ do+ putStrLn (show n ++ " properties failed")+ exitFailure++runTests :: IO ()+runTests = do+ putStrLn "Int tests:" check_Int_sort check_Int_sortUniq check_Int_partialsort@@ -228,3 +448,17 @@ check_corners putStrLn "Algorithms:" check_nub+ putStrLn "Large structured inputs:"+ check_large+ putStrLn "Sub-range (ByBounds) operations:"+ check_bounds+ putStrLn "Heap operations:"+ check_heap_ops+ putStrLn "Introsort worst-case inputs:"+ check_killer+ putStrLn "American flag sort on compound types:"+ check_flag_compound+ putStrLn "Searching:"+ check_search+ putStrLn "Unboxed, storable and primitive vectors:"+ check_vector_types
tests/properties/Util.hs view
@@ -7,6 +7,7 @@ import Data.Word import Data.Int+import qualified Data.List as L import qualified Data.ByteString as B @@ -31,3 +32,137 @@ instance Arbitrary B.ByteString where arbitrary = B.pack `fmap` arbitrary ++-- | A large vector of 'Int' keys with a particular structure.+--+-- The default QuickCheck size limit keeps ordinary 'Arbitrary' vectors under+-- about 100 elements, which is too small to reach the run merging and+-- galloping code in Tim sort, the deeper merge levels of merge sort, or the+-- heap sort fallback in introsort. This generator produces vectors with+-- thousands of elements, in shapes that commonly expose sorting bugs.+data LargeVec = LargeVec String (V.Vector Int)++instance Show LargeVec where+ show (LargeVec shape v) =+ "LargeVec " ++ shape ++ " (length " ++ show (V.length v) ++ ") " ++ show v++instance Arbitrary LargeVec where+ arbitrary = do+ n <- choose (64, 5000)+ (shape, gen) <- elements largeShapes+ LargeVec shape . V.fromList <$> gen n++ -- Shrinking does not preserve the shape, but any smaller failing vector is+ -- still a valid (and more readable) counterexample.+ shrink (LargeVec shape v)+ | len < 2 = []+ | otherwise = [ LargeVec shape (V.take half v)+ , LargeVec shape (V.drop half v)+ , LargeVec shape (V.take (len - 1) v)+ , LargeVec shape (V.drop 1 v)+ ]+ where+ len = V.length v+ half = len `div` 2++largeShapes :: [(String, Int -> Gen [Int])]+largeShapes =+ [ ("random", \n -> vectorOf n (choose (-n, n)))+ , ("few-distinct", \n -> vectorOf n (choose (0, 4)))+ , ("all-equal", \n -> pure (Prelude.replicate n 7))+ , ("ascending", \n -> pure [1 .. n])+ , ("ascending-dups", \n -> scanl1 (+) <$> vectorOf n (choose (0, 1)))+ , ("descending", \n -> pure [n, n - 1 .. 1])+ , ("descending-dups", \n -> scanl1 (-) <$> vectorOf n (choose (0, 1)))+ , ("organ-pipe", \n -> let h = n `div` 2+ in pure ([1 .. h] ++ [n - h, n - h - 1 .. 1]))+ , ("sawtooth", \n -> do m <- choose (2, 200)+ pure [ i `mod` m | i <- [0 .. n - 1] ])+ , ("sorted-runs", sortedRuns)+ , ("nearly-sorted", nearlySorted)+ , ("sorted-tail", \n -> do k <- choose (1, 20)+ t <- vectorOf k (choose (-n, n))+ pure ([1 .. n - k] ++ t))+ ]++-- | Concatenated ascending runs of random lengths. Runs drawn from disjoint+-- value ranges make Tim sort's galloping mode kick in.+sortedRuns :: Int -> Gen [Int]+sortedRuns n = go n+ where+ go 0 = pure []+ go r = do+ len <- choose (1, min r 300)+ base <- choose (-n, n)+ step <- choose (0, 3)+ rest <- go (r - len)+ pure (Prelude.take len [base, base + step ..] ++ rest)++-- | An ascending sequence with a few random elements swapped.+nearlySorted :: Int -> Gen [Int]+nearlySorted n = do+ k <- choose (1, 10)+ swaps <- vectorOf k ((,) <$> choose (0, n - 1) <*> choose (0, n - 1))+ -- Apply the swaps in turn, so the result is a permutation of [1 .. n].+ pure . V.toList $ V.modify (\mv -> Control.Monad.mapM_ (uncurry (swap mv)) swaps) (V.fromList [1 .. n])++-- | A vector together with a sub-range [l, u) of it and a count k with+-- 0 <= k <= u - l, for testing the @...ByBounds@ functions. The vector is+-- either a small arbitrary one or a 'LargeVec'.+data BoundsCase = BoundsCase (V.Vector Int) Int Int Int++instance Show BoundsCase where+ show (BoundsCase v l u k) =+ "BoundsCase (length " ++ show (V.length v) ++ ") l=" ++ show l+ ++ " u=" ++ show u ++ " k=" ++ show k ++ " " ++ show v++instance Arbitrary BoundsCase where+ arbitrary = do+ v <- oneof [ V.fromList <$> listOf (choose (-20, 20))+ , (\(LargeVec _ lv) -> lv) <$> arbitrary+ ]+ let n = V.length v+ l <- choose (0, n)+ u <- choose (l, n)+ k <- choose (0, u - l)+ pure (BoundsCase v l u k)++ shrink (BoundsCase v l u k) =+ [ BoundsCase (V.take u v) l u k | u < n ]+ ++ [ BoundsCase (V.take (u + (n - u) `div` 2) v) l u k | n - u > 1 ]+ ++ [ BoundsCase (V.drop l v) 0 (u - l) k | l > 0 ]+ ++ [ BoundsCase (V.drop (l `div` 2) v) (l - l `div` 2) (u - l `div` 2) k | l > 1 ]+ ++ [ BoundsCase (V.take a v V.++ V.drop b v) l (u - d) (min k (u - l - d))+ | (a, b) <- cuts, b > a, let d = b - a ]+ ++ [ BoundsCase v l u (k `div` 2) | k > 0 ]+ where+ n = V.length v+ half = (u - l) `div` 2+ -- Remove the upper half, lower half or last element of [l, u). An empty+ -- range has nothing to cut, and (u - 1, u) would lie outside it.+ cuts | u > l = [(l + half, u), (l, l + half), (u - 1, u)]+ | otherwise = []++-- | A sorted vector together with a sub-range [l, u) of it and a key to+-- search for, which is either one of the elements in the range or an+-- arbitrary value.+data SearchCase = SearchCase (V.Vector Int) Int Int Int++instance Show SearchCase where+ show (SearchCase v l u e) =+ "SearchCase (length " ++ show (V.length v) ++ ") l=" ++ show l+ ++ " u=" ++ show u ++ " e=" ++ show e ++ " " ++ show v++instance Arbitrary SearchCase where+ arbitrary = do+ BoundsCase v0 l u _ <- arbitrary+ let v = V.fromList (L.sort (V.toList v0))+ e <- if u > l+ then oneof [ (v V.!) <$> choose (l, u - 1), choose (-50, 50)+ , pure (minBound + 1), pure (maxBound - 1) ]+ else choose (-50, 50)+ pure (SearchCase v l u e)++ -- Shrinking only removes elements, so the vector stays sorted.+ shrink (SearchCase v l u e) =+ [ SearchCase v' l' u' e | BoundsCase v' l' u' _ <- shrink (BoundsCase v l u 0) ]
vector-algorithms.cabal view
@@ -1,6 +1,6 @@ cabal-version: >= 1.10 name: vector-algorithms-version: 0.9.1.0+version: 0.9.1.1 license: BSD3 license-file: LICENSE author: Dan Doel@@ -18,18 +18,18 @@ extra-source-files: CHANGELOG.md tested-with:- GHC == 9.12.1- GHC == 9.10.1- GHC == 9.8.2- GHC == 9.6.3- GHC == 9.4.7+ GHC == 9.14.1+ GHC == 9.12.2+ GHC == 9.10.2+ GHC == 9.8.4+ GHC == 9.6.7+ GHC == 9.4.8 GHC == 9.2.8 GHC == 9.0.2 GHC == 8.10.7 GHC == 8.8.4 GHC == 8.6.5 GHC == 8.4.4- GHC == 8.2.2 flag BoundsChecks description: Enable bounds checking@@ -73,7 +73,7 @@ bytestring >= 0.9 && < 1 if ! impl (ghc >= 7.8)- build-depends: tagged >= 0.4 && < 0.9+ build-depends: tagged >= 0.4 && < 0.10 exposed-modules: Data.Vector.Algorithms@@ -93,6 +93,14 @@ ghc-options: -funbox-strict-fields + -- The same warnings that CI (see .github/workflows/haskell-ci.yml) turns+ -- into errors.+ ghc-options: -Wmissing-methods -Wmissing-fields+ if impl(ghc >= 9.0)+ ghc-options: -Wincomplete-patterns -Wincomplete-uni-patterns+ if impl(ghc >= 9.4)+ ghc-options: -Wunused-packages+ -- Cabal/Hackage complains about these -- if flag(dump-simpl) -- ghc-options: -ddump-simpl -ddump-to-file@@ -131,6 +139,14 @@ build-depends: base, mwc-random, vector, vector-algorithms ghc-options: -Wall + -- The same warnings that CI (see .github/workflows/haskell-ci.yml) turns+ -- into errors.+ ghc-options: -Wmissing-methods -Wmissing-fields+ if impl(ghc >= 9.0)+ ghc-options: -Wincomplete-patterns -Wincomplete-uni-patterns+ if impl(ghc >= 9.4)+ ghc-options: -Wunused-packages+ -- Cabal/Hackage complains about these -- if flag(dump-simpl) -- ghc-options: -ddump-simpl -ddump-to-file@@ -145,6 +161,7 @@ default-language: Haskell2010 other-modules:+ Adversary Optimal Properties Util@@ -153,9 +170,17 @@ base >= 4.9, bytestring, containers,- QuickCheck > 2.9 && < 2.16,+ QuickCheck > 2.9 && < 2.20, vector, vector-algorithms++ -- The same warnings that CI (see .github/workflows/haskell-ci.yml) turns+ -- into errors.+ ghc-options: -Wmissing-methods -Wmissing-fields+ if impl(ghc >= 9.0)+ ghc-options: -Wincomplete-patterns -Wincomplete-uni-patterns+ if impl(ghc >= 9.4)+ ghc-options: -Wunused-packages if flag(llvm) ghc-options: -fllvm