@@ -2,15 +2,20 @@ module Test.Main where
22
33import Prelude
44
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 (..))
912
1013import Control.Monad.Eff (Eff )
1114import Control.Monad.Eff.Console (CONSOLE , logShow )
1215import Control.Monad.State (evalState , get )
1316
17+
18+ -- Traversing an array nested within a record
1419foo :: forall a b r . Lens { foo :: a | r } { foo :: b | r } a b
1520foo = lens _.foo (_ { foo = _ })
1621
@@ -25,11 +30,31 @@ doc = { foo: Just { bar: [ "Hello", " ", "World" ]} }
2530bars :: forall a b . Traversal (Foo a ) (Foo b ) a b
2631bars = foo <<< _Just <<< bar <<< traversed
2732
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
2852stateTest :: Tuple Int String
2953stateTest = evalState go (Tuple 4 [" Foo" , " Bar" ]) where
3054 go = Tuple <$> zoom _1 get <*> zoom (_2 <<< traversed) get
3155
3256main :: forall e . Eff (console :: CONSOLE | e ) Unit
3357main = do
3458 logShow $ view bars doc
59+ logShow $ doc2 ^? _1bars
3560 logShow stateTest
0 commit comments