@@ -6,43 +6,44 @@ module Data.Lens.Index
6
6
import Prelude
7
7
8
8
import Data.Array as A
9
+ import Data.Array.NonEmpty as NEA
9
10
import Data.Identity (Identity )
10
11
import Data.Lens.Internal.Wander (wander )
11
12
import Data.Lens.Types (Traversal' )
12
13
import Data.Map as M
13
14
import Data.Maybe (Maybe , maybe , fromMaybe )
14
15
import Data.Set as S
15
- import Foreign.Object as FO
16
16
import Data.Traversable (traverse )
17
+ import Foreign.Object as FO
17
18
18
19
-- | `Index` is a type class whose instances are optics used when:
19
20
-- | 1. The focus element might not be present.
20
- -- | 2. You either cannot or do not want to add new elements or delete existing ones.
21
+ -- | 2. You either cannot or do not want to add new elements or delete existing ones.
21
22
-- |
22
23
-- | `Array` is a typical example:
23
24
-- |
24
- -- | ```purescript
25
+ -- | ```purescript
25
26
-- | preview (ix 1) [0, 1, 2] == Just 1
26
27
-- |
27
28
-- | set (ix 1) 8888 [0, 1, 2] == [0,8888,2]
28
29
-- | ```
29
30
-- |
30
- -- | Note the use of `preview` rather `view`. That's because the optic is
31
+ -- | Note the use of `preview` rather `view`. That's because the optic is
31
32
-- | a `Data.Lens.Traversal` tailored to the case where there's a single element
32
33
-- | of interest.
33
- -- |
34
+ -- |
34
35
-- | Another common use is a `Map` that you don't want to either grow or shrink:
35
36
-- |
36
- -- | ```purescript
37
+ -- | ```purescript
37
38
-- | (set (ix "k") "new" $ Map.singleton "k" "old") == Map.singleton "k" "new"
38
- -- |
39
+ -- |
39
40
-- | (set (ix "k") "new" $ Map.empty) == Map.empty
40
41
-- | ```
41
42
-- |
42
43
-- | Note the second line: an attempt to `set` a missing focus element
43
44
-- | leaves the original whole unchanged.
44
45
-- |
45
- -- | If you *do* want to add or delete elements, see `Data.Lens.At`.
46
+ -- | If you *do* want to add or delete elements, see `Data.Lens.At`.
46
47
47
48
class Index m a b | m -> a , m -> b where
48
49
ix :: a -> Traversal' m b
@@ -67,6 +68,14 @@ instance indexArray :: Index (Array a) Int a where
67
68
(pure xs)
68
69
(coalg >>> map \x -> fromMaybe xs (A .updateAt n x xs))
69
70
71
+ instance indexNonEmptyArray :: Index (NEA.NonEmptyArray a ) Int a where
72
+ ix n =
73
+ wander \coalg xs ->
74
+ xs NEA .!! n #
75
+ maybe
76
+ (pure xs)
77
+ (coalg >>> map \x -> fromMaybe xs (NEA .updateAt n x xs))
78
+
70
79
instance indexSet :: Ord a => Index (S.Set a ) a Unit where
71
80
ix x =
72
81
wander \coalg ->
0 commit comments