@@ -2,15 +2,20 @@ module Test.Main where
2
2
3
3
import Prelude
4
4
5
- import Data.Maybe (Maybe (..))
6
- import Data.Lens (view , traversed , _1 , _2 , _Just , lens )
7
- import Data.Lens.Zoom (Traversal , Lens , zoom )
8
- import Data.Tuple (Tuple (..))
5
+ import Data.Lens (view , traversed , _1 , _2 , _Just , _Left , lens )
6
+ import Data.Lens.Index (ix )
7
+ import Data.Lens.Fold ((^?))
8
+ import Data.Lens.Zoom (Traversal , TraversalP , Lens , LensP , zoom )
9
+ import Data.Tuple (Tuple (..))
10
+ import Data.Maybe (Maybe (..))
11
+ import Data.Either (Either (..))
9
12
10
13
import Control.Monad.Eff (Eff )
11
14
import Control.Monad.Eff.Console (CONSOLE , logShow )
12
15
import Control.Monad.State (evalState , get )
13
16
17
+
18
+ -- Traversing an array nested within a record
14
19
foo :: forall a b r . Lens { foo :: a | r } { foo :: b | r } a b
15
20
foo = lens _.foo (_ { foo = _ })
16
21
@@ -25,11 +30,31 @@ doc = { foo: Just { bar: [ "Hello", " ", "World" ]} }
25
30
bars :: forall a b . Traversal (Foo a ) (Foo b ) a b
26
31
bars = foo <<< _Just <<< bar <<< traversed
27
32
33
+
34
+ -- Get the index of a deeply nested record
35
+ type BarRec = { foo :: Array (Either { bar :: Array Int } String ) }
36
+ data Bar = Bar BarRec
37
+
38
+ _Bar :: LensP Bar BarRec
39
+ _Bar = lens (\(Bar rec) -> rec) (\_ -> Bar )
40
+
41
+ doc2 :: Bar
42
+ doc2 = Bar { foo: [Left { bar: [ 1 , 2 , 3 ] }] }
43
+
44
+ _0Justbar :: TraversalP Bar (Either { bar :: Array Int } String )
45
+ _0Justbar = _Bar <<< foo <<< ix 0
46
+
47
+ _1bars :: TraversalP Bar Int
48
+ _1bars = _0Justbar <<< _Left <<< bar <<< ix 1
49
+
50
+
51
+ -- Tests state using zoom
28
52
stateTest :: Tuple Int String
29
53
stateTest = evalState go (Tuple 4 [" Foo" , " Bar" ]) where
30
54
go = Tuple <$> zoom _1 get <*> zoom (_2 <<< traversed) get
31
55
32
56
main :: forall e . Eff (console :: CONSOLE | e ) Unit
33
57
main = do
34
58
logShow $ view bars doc
59
+ logShow $ doc2 ^? _1bars
35
60
logShow stateTest
0 commit comments