From d1bc42e40d8e9b883b8ee62814f618eb14372494 Mon Sep 17 00:00:00 2001 From: Cyril Date: Wed, 23 Dec 2020 22:20:20 +0100 Subject: [PATCH] Add new and run to Record.ST (#71) * Add Record.ST.new * Add Record.ST.run * Copy changes to Foreign.Object.run documentation --- src/Record/ST.js | 8 ++++++++ src/Record/ST.purs | 11 +++++++++++ test/Main.purs | 7 +++---- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/Record/ST.js b/src/Record/ST.js index 70c20b0..4ea7d15 100644 --- a/src/Record/ST.js +++ b/src/Record/ST.js @@ -1,5 +1,13 @@ "use strict"; +exports.run = function (f) { + return f(); +}; + +exports["new"] = function () { + return {}; +}; + function copyRecord(rec) { var copy = {}; for (var key in rec) { diff --git a/src/Record/ST.purs b/src/Record/ST.purs index e68f219..b078723 100644 --- a/src/Record/ST.purs +++ b/src/Record/ST.purs @@ -1,5 +1,7 @@ module Record.ST ( STRecord + , run + , new , freeze , thaw , peek @@ -21,6 +23,15 @@ foreign import data STRecord :: Region -> Row Type -> Type type role STRecord nominal representational +-- | Freeze a mutable record, creating an immutable record. Use this function as you would use +-- | `Control.Monad.ST.run` (from the `purescript-st` package) to freeze a mutable reference. +-- | +-- | The rank-2 type prevents the record from escaping the scope of `run`. +foreign import run :: forall r. (forall h. ST h (STRecord h r)) -> Record r + +-- | Create a new, empty mutable record +foreign import new :: forall h. ST h (STRecord h ()) + -- | Freeze a mutable record, creating a copy. foreign import freeze :: forall h r. STRecord h r -> ST h (Record r) diff --git a/test/Main.purs b/test/Main.purs index 606ef76..e98e5e1 100644 --- a/test/Main.purs +++ b/test/Main.purs @@ -5,8 +5,7 @@ import Prelude import Effect (Effect) import Record (delete, equal, get, insert, merge, modify, rename, set) import Record.Builder as Builder -import Control.Monad.ST (run) as ST -import Record.ST (poke, thaw, freeze, modify) as ST +import Record.ST (run, poke, thaw, modify) as ST import Record.Unsafe (unsafeHas) import Test.Assert (assert') import Type.Proxy (Proxy(..)) @@ -45,11 +44,11 @@ main = do rec <- ST.thaw { x: 41, y: "" } ST.poke x 42 rec ST.poke y "testing" rec - ST.freeze rec + pure rec stTest2 = ST.run do rec <- ST.thaw { x: 41 } ST.modify x (_ + 1) rec - ST.freeze rec + pure rec assert' "pokeSTRecord" $ stTest1.x == 42 && stTest1.y == "testing"