-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
faster traversable sorting with the help of vector-algorithms #2
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
{-# LANGUAGE Rank2Types #-} | ||
{-# LANGUAGE ScopedTypeVariables #-} | ||
module Data.Traversable.Sort.Vector (sortTraversableBy, sortTraversable) where | ||
import Control.Monad.ST.Strict | ||
import Control.Monad.State.Strict | ||
import Data.Foldable | ||
import qualified Data.Vector.Algorithms.Intro as Intro | ||
import qualified Data.Vector.Mutable as VM | ||
|
||
{-# INLINE sortTraversableBy #-} | ||
sortTraversableBy :: (Ord a, Traversable f) | ||
=> (forall s. VM.STVector s a -> ST s ()) | ||
-> f a | ||
-> f a | ||
sortTraversableBy sort val = runST (do | ||
vec <- indexed val | ||
sort vec | ||
evalStateT (traverse | ||
(\_ -> StateT | ||
(\i -> do | ||
r <- VM.unsafeRead vec i | ||
return (r, i + 1))) | ||
val) | ||
(0 :: Int)) | ||
|
||
{-# INLINE sortTraversable #-} | ||
-- | Sort a traversable container using introsort from vector-algorithms. | ||
sortTraversable :: (Ord a, Traversable f) => f a -> f a | ||
sortTraversable = sortTraversableBy Intro.sort | ||
|
||
data P s a = P | ||
{-# UNPACK #-} !Int | ||
!(VM.STVector s a -> ST s ()) | ||
|
||
{-# INLINE indexed #-} | ||
indexed :: forall f a s. (Ord a, Foldable f) => f a -> ST s (VM.STVector s a) | ||
indexed x = do | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think this implementation is the right approach. A left fold is too weird here, and you're building up a big closure chain. Why not just use the conversion |
||
case foldl' | ||
(\(P i f) el -> P | ||
(i + 1) | ||
(\v -> f v >> VM.unsafeWrite v i el)) | ||
(P 0 (\_ -> return ()) :: P s a) | ||
x of | ||
P len initFn -> do | ||
vec <- VM.unsafeNew len | ||
initFn vec | ||
return vec | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This name is confusing. This is not actually a sorting function at all, and the
Ord
constraint isn't needed.