module Data.Vector.Instances () where
import Prelude hiding ((++), drop, length)
import Control.Applicative
import Control.Monad
import Data.Semigroup
import Data.Key
import Data.Functor.Bind
import Data.Functor.Extend
import Data.Functor.Plus
import Data.Foldable (Foldable(..))
import Data.Traversable (Traversable(..))
import Data.Pointed
import Data.Monoid
import qualified Data.Vector as Vector
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Fusion.Stream as Stream
import Data.Vector.Fusion.Stream.Size
import Data.Vector (Vector,(++),drop,length,imap,ifoldr, ifoldl, izipWith,(!?),(//), generate)
import qualified Data.Vector as Vector
instance Functor Vector where
fmap = Vector.map
type instance Key Vector = Int
instance Keyed Vector where
mapWithKey = imap
instance Zip Vector where
zipWith = Vector.zipWith
instance ZipWithKey Vector where
zipWithKey = Vector.izipWith
instance Indexable Vector where
index = (!)
instance Lookup Vector where
lookup = flip (!?)
instance Adjustable Vector where
adjust f n v = case v !? n of
Just a -> v // [(n, f a)]
Nothing -> v
replace n a v = v // [(n,a)]
instance FoldableWithKey Vector where
foldrWithKey = ifoldr
foldlWithKey = ifoldl
instance Apply Vector where
fs <.> as =
G.unstream $ Stream.sized results (Exact n)
where
n = Vector.length fs * Vector.length as
results = Stream.concatMap body $ G.stream fs
body f = Stream.map f $ G.stream as
instance Pointed Vector where
point = Vector.singleton
instance Applicative Vector where
pure = Vector.singleton
fs <*> as =
G.unstream $ Stream.sized results (Exact n)
where
n = Vector.length fs * Vector.length as
results = Stream.concatMap body $ G.stream fs
body f = Stream.map f $ G.stream as
instance Bind Vector where
v >>- f = Vector.concatMap f v
instance Semigroup (Vector a) where
(<>) = (++)
instance Monad Vector where
return = Vector.singleton
v >>= f = Vector.concatMap f v
fail _ = Vector.empty
instance MonadPlus Vector where
mzero = Vector.empty
mplus = (++)
instance Alt Vector where
(<!>) = (++)
instance Plus Vector where
zero = Vector.empty
instance Alternative Vector where
(<|>) = (++)
empty = Vector.empty
instance Foldable Vector where
foldl = Vector.foldl
foldr = Vector.foldr
foldl1 = Vector.foldl1
foldr1 = Vector.foldr1
instance Traversable Vector where
traverse f v
= Vector.fromListN (Vector.length v) <$> traverse f (Vector.toList v)
instance TraversableWithKey Vector where
traverseWithKey f v
= Vector.fromListN (Vector.length v) <$> traverseWithKey f (Vector.toList v)
instance Extend Vector where
duplicate v = generate (length v) (`drop` v)
extend f v = generate (length v) (\n -> f (drop n v))