File tree Expand file tree Collapse file tree 3 files changed +37
-0
lines changed Expand file tree Collapse file tree 3 files changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -6,6 +6,14 @@ exports.new = function (val) {
6
6
} ;
7
7
} ;
8
8
9
+ exports . newWithSelf = function ( f ) {
10
+ return function ( ) {
11
+ var ref = { value : null } ;
12
+ ref . value = f ( ref ) ;
13
+ return ref ;
14
+ } ;
15
+ } ;
16
+
9
17
exports . read = function ( ref ) {
10
18
return function ( ) {
11
19
return ref . value ;
Original file line number Diff line number Diff line change 22
22
module Effect.Ref
23
23
( Ref
24
24
, new
25
+ , newWithSelf
25
26
, read
26
27
, modify'
27
28
, modify
@@ -42,6 +43,10 @@ type role Ref representational
42
43
-- | Create a new mutable reference containing the specified value.
43
44
foreign import new :: forall s . s -> Effect (Ref s )
44
45
46
+ -- | Create a new mutable reference containing a value that can refer to the
47
+ -- | `Ref` being created.
48
+ foreign import newWithSelf :: forall s . (Ref s -> s ) -> Effect (Ref s )
49
+
45
50
-- | Read the current value of a mutable reference.
46
51
foreign import read :: forall s . Ref s -> Effect s
47
52
Original file line number Diff line number Diff line change @@ -28,3 +28,27 @@ main = do
28
28
-- now it is 2 when we read out the value
29
29
curr3 <- Ref .read ref
30
30
assertEqual { actual: curr3, expected: 2 }
31
+
32
+ selfRef
33
+
34
+ newtype RefBox = RefBox { ref :: Ref.Ref RefBox , value :: Int }
35
+
36
+ selfRef :: Effect Unit
37
+ selfRef = do
38
+ -- Create a self-referential `Ref`
39
+ ref <- Ref .newWithSelf \ref -> RefBox { ref, value: 0 }
40
+
41
+ -- Grab the `Ref` from within the `Ref`
42
+ ref' <- Ref .read ref <#> \(RefBox r) -> r.ref
43
+
44
+ -- Modify the `ref` and check that value in `ref'` changes
45
+ Ref .modify_ (\(RefBox r) -> RefBox (r { value = 1 })) ref
46
+ assertEqual
47
+ <<< { expected: 1 , actual: _ }
48
+ =<< (Ref .read ref' <#> \(RefBox { value }) -> value)
49
+
50
+ -- Modify the `ref'` and check that value in `ref` changes
51
+ Ref .modify_ (\(RefBox r) -> RefBox (r { value = 2 })) ref'
52
+ assertEqual
53
+ <<< { expected: 2 , actual: _ }
54
+ =<< (Ref .read ref <#> \(RefBox { value }) -> value)
You can’t perform that action at this time.
0 commit comments