Skip to content

Commit 81024d7

Browse files
authored
Made indexList more efficient
Only traverse the list at most once.
1 parent 9cb69f5 commit 81024d7

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

src/Data/Lens/Index.purs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@ import Data.Array.NonEmpty as NEA
1010
import Data.Identity (Identity)
1111
import Data.Lens.Internal.Wander (wander)
1212
import Data.Lens.Types (Traversal')
13-
import Data.List (List)
14-
import Data.List as L
13+
import Data.List (List(..), (:))
1514
import Data.Map as M
1615
import Data.Maybe (Maybe, maybe, fromMaybe)
1716
import Data.Set as S
@@ -79,12 +78,12 @@ instance indexNonEmptyArray :: Index (NEA.NonEmptyArray a) Int a where
7978
(coalg >>> map \x -> fromMaybe xs (NEA.updateAt n x xs))
8079

8180
instance indexList :: Index (List a) Int a where
82-
ix n =
83-
wander \coalg xs ->
84-
xs L.!! n #
85-
maybe
86-
(pure xs)
87-
(coalg >>> map \x -> fromMaybe xs (L.updateAt n x xs))
81+
ix n | n < 0 = wander \_ xs -> pure xs
82+
| otherwise = wander \coalg xs -> go xs n coalg where
83+
go :: forall f. Applicative f => List a -> Int -> (a -> f a) -> f (List a)
84+
go Nil _ _ = pure Nil
85+
go (a:as) 0 coalg = coalg a <#> (_:as)
86+
go (a:as) i coalg = (a:_) <$> (go as (i - 1) coalg)
8887

8988
instance indexSet :: Ord a => Index (S.Set a) a Unit where
9089
ix x =

0 commit comments

Comments
 (0)