Skip to content

ST.modify #37

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 2 commits into from
May 22, 2018
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
10 changes: 10 additions & 0 deletions src/Record/ST.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,13 @@ exports.unsafePoke = function(l) {
};
};
};

exports.unsafeModify = function(l) {
return function(f) {
return function(rec) {
return function() {
rec[l] = f(rec[l]);
};
};
};
};
21 changes: 21 additions & 0 deletions src/Record/ST.purs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module Record.ST
, thaw
, peek
, poke
, modify
) where

import Prelude
Expand Down Expand Up @@ -59,3 +60,23 @@ poke
-> STRecord h r
-> ST h Unit
poke l = unsafePoke (reflectSymbol l)

foreign import unsafeModify
:: forall a r h
. String
-> (a -> a)
-> STRecord h r
-> ST h Unit

-- | Modify a record in place,
-- | by providing a type-level representative for the label to update
-- | and a function to update it.
modify
:: forall l h a r r1
. Row.Cons l a r1 r
=> IsSymbol l
=> SProxy l
-> (a -> a)
-> STRecord h r
-> ST h Unit
modify l = unsafeModify (reflectSymbol l)
18 changes: 12 additions & 6 deletions test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Effect (Effect)
import Record (delete, equal, get, insert, modify, rename, set)
import Record.Builder as Builder
import Control.Monad.ST (run) as ST
import Record.ST (poke, thaw, freeze) as ST
import Record.ST (poke, thaw, freeze, modify) as ST
import Record.Unsafe (unsafeHas)
import Data.Symbol (SProxy(..))
import Test.Assert (assert')
Expand Down Expand Up @@ -38,14 +38,20 @@ main = do
assert' "unsafeHas2" $
not $ unsafeHas "b" { a: 42 }

let stTest1 = ST.run do
rec <- ST.thaw { x: 41, y: "" }
ST.poke x 42 rec
ST.poke y "testing" rec
ST.freeze rec
let
stTest1 = ST.run do
rec <- ST.thaw { x: 41, y: "" }
ST.poke x 42 rec
ST.poke y "testing" rec
ST.freeze rec
stTest2 = ST.run do
rec <- ST.thaw { x: 41 }
ST.modify x (_ + 1) rec
ST.freeze rec

assert' "pokeSTRecord" $
stTest1.x == 42 && stTest1.y == "testing"
assert' "ST.modify" $ stTest2.x == 42

let testBuilder = Builder.build (Builder.insert x 42
>>> Builder.merge { y: true, z: "testing" }
Expand Down