@@ -13,11 +13,12 @@ import Prelude
13
13
14
14
import Control.Monad.Gen.Class (class MonadGen , Size , chooseBool , chooseFloat , chooseInt , resize , sized )
15
15
import Control.Monad.Rec.Class (class MonadRec , Step (..), tailRecM )
16
- import Data.Foldable (foldMap , length )
16
+ import Data.Foldable (foldMap , foldr , length )
17
17
import Data.Maybe (Maybe (..))
18
18
import Data.Monoid.Additive (Additive (..))
19
- import Data.Newtype (alaF )
19
+ import Data.Newtype (alaF , un )
20
20
import Data.Semigroup.Foldable (class Foldable1 , foldMap1 )
21
+ import Data.Semigroup.Last (Last (..))
21
22
import Data.Tuple (Tuple (..), fst , snd )
22
23
import Data.Unfoldable (class Unfoldable , unfoldr )
23
24
@@ -118,22 +119,14 @@ filtered gen = tailRecM go unit
118
119
Nothing -> Loop unit
119
120
Just a' -> Done a'
120
121
121
- -- | Internal: used by fromIndex
122
- newtype AtIndex a = AtIndex (Int -> a )
123
-
124
- instance semigroupAtIndex :: Semigroup (AtIndex a )
125
- where
126
- append (AtIndex f) (AtIndex g) =
127
- AtIndex \i -> if i <= 0 then f i else g (i - 1 )
128
-
129
- atIndex :: forall a . a -> AtIndex a
130
- atIndex = AtIndex <<< const
131
-
132
- getAtIndex :: forall a . AtIndex a -> Int -> a
133
- getAtIndex (AtIndex f) = f
134
-
135
122
-- | Internal: get the Foldable element at index i.
136
123
-- | If the index is <= 0, return the first element.
137
124
-- | If it's >= length, return the last.
138
125
fromIndex :: forall f a . Foldable1 f => Int -> f a -> a
139
- fromIndex i xs = getAtIndex (foldMap1 atIndex xs) i
126
+ fromIndex i xs = go i (foldr Cons Nil xs)
127
+ where
128
+ go _ (Cons a Nil ) = a
129
+ go j (Cons a _) | j <= 0 = a
130
+ go j (Cons _ as) = go (j - 1 ) as
131
+ -- next case is "impossible", but serves as proof of non-emptyness
132
+ go _ Nil = un Last (foldMap1 Last xs)
0 commit comments