Skip to content

Allow the construction of self-referential Refs #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/Effect/Ref.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ exports.new = function (val) {
};
};

exports.newWithSelf = function (f) {
return function () {
var ref = { value: null };
ref.value = f(ref);
return ref;
};
};

exports.read = function (ref) {
return function () {
return ref.value;
Expand Down
5 changes: 5 additions & 0 deletions src/Effect/Ref.purs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
module Effect.Ref
( Ref
, new
, newWithSelf
, read
, modify'
, modify
Expand All @@ -42,6 +43,10 @@ type role Ref representational
-- | Create a new mutable reference containing the specified value.
foreign import new :: forall s. s -> Effect (Ref s)

-- | Create a new mutable reference containing a value that can refer to the
-- | `Ref` being created.
foreign import newWithSelf :: forall s. (Ref s -> s) -> Effect (Ref s)

-- | Read the current value of a mutable reference.
foreign import read :: forall s. Ref s -> Effect s

Expand Down
24 changes: 24 additions & 0 deletions test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,27 @@ main = do
-- now it is 2 when we read out the value
curr3 <- Ref.read ref
assertEqual { actual: curr3, expected: 2 }

selfRef

newtype RefBox = RefBox { ref :: Ref.Ref RefBox, value :: Int }

selfRef :: Effect Unit
selfRef = do
-- Create a self-referential `Ref`
ref <- Ref.newWithSelf \ref -> RefBox { ref, value: 0 }

-- Grab the `Ref` from within the `Ref`
ref' <- Ref.read ref <#> \(RefBox r) -> r.ref

-- Modify the `ref` and check that value in `ref'` changes
Ref.modify_ (\(RefBox r) -> RefBox (r { value = 1 })) ref
assertEqual
<<< { expected: 1, actual: _ }
=<< (Ref.read ref' <#> \(RefBox { value }) -> value)

-- Modify the `ref'` and check that value in `ref` changes
Ref.modify_ (\(RefBox r) -> RefBox (r { value = 2 })) ref'
assertEqual
<<< { expected: 2, actual: _ }
=<< (Ref.read ref <#> \(RefBox { value }) -> value)