{-# LANGUAGE CPP #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE FlexibleContexts #-}
#ifdef TRUSTWORTHY
{-# LANGUAGE Trustworthy #-}
#endif
module Data.Vector.Generic.Lens
( toVectorOf
, forced
, vector
, asStream
, asStreamR
, cloned
, sliced
, ordinals
) where
import Control.Applicative
import Control.Lens
import Data.List (nub)
import Data.Monoid
import Data.Vector.Generic as V hiding (zip, filter, indexed)
import Data.Vector.Fusion.Stream (Stream)
import Data.Vector.Generic.New (New)
import Prelude hiding ((++), length, null, head, tail, init, last, map, reverse)
sliced :: Vector v a
=> Int
-> Int
-> Lens' (v a) (v a)
sliced i n f v = f (slice i n v) <&> \ v0 -> v // zip [i..i+n-1] (V.toList v0)
{-# INLINE sliced #-}
toVectorOf :: Vector v a => Getting (Endo [a]) s a -> s -> v a
toVectorOf l s = fromList (toListOf l s)
{-# INLINE toVectorOf #-}
vector :: Vector v a => Iso' [a] (v a)
vector = iso fromList V.toList
{-# INLINE vector #-}
asStream :: Vector v a => Iso' (v a) (Stream a)
asStream = iso stream unstream
{-# INLINE asStream #-}
asStreamR :: Vector v a => Iso' (v a) (Stream a)
asStreamR = iso streamR unstreamR
{-# INLINE asStreamR #-}
cloned :: Vector v a => Iso' (v a) (New v a)
cloned = iso clone new
{-# INLINE cloned #-}
forced :: Vector v a => Iso' (v a) (v a)
forced = involuted force
{-# INLINE forced #-}
ordinals :: Vector v a => [Int] -> IndexedTraversal' Int (v a) a
ordinals is f v = fmap (v //) $ traverse (\i -> (,) i <$> indexed f i (v ! i)) $ nub $ filter (\i -> 0 <= i && i < l) is where
l = length v
{-# INLINE ordinals #-}