Skip to content

Commit

Permalink
Add clone to Data.Array.ST (#243)
Browse files Browse the repository at this point in the history
* Add copy to Data.Array.ST

* rename copy with clone

* modify the original array in the clone test to prove that the cloned array is a copy

* update CHANGELOG.md
  • Loading branch information
gbagan authored Nov 2, 2023
1 parent 7286121 commit d521e17
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Notable changes to this project are documented in this file. The format is based
Breaking changes:

New features:
- Add `ST.clone` (#243 by @Bgbagan)

Bugfixes:

Expand Down
2 changes: 2 additions & 0 deletions src/Data/Array/ST.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export const freezeImpl = copyImpl;

export const thawImpl = copyImpl;

export const cloneImpl = copyImpl;

export const sortByImpl = (function () {
function mergeFromTo(compare, fromOrdering, xs1, xs2, from, to) {
var mid;
Expand Down
10 changes: 10 additions & 0 deletions src/Data/Array/ST.purs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ module Data.Array.ST
, sortWith
, freeze
, thaw
, clone
, unsafeFreeze
, unsafeThaw
, toAssocArray
Expand Down Expand Up @@ -95,6 +96,15 @@ thaw = runSTFn1 thawImpl
-- | Create a mutable copy of an immutable array.
foreign import thawImpl :: forall h a. STFn1 (Array a) h (STArray h a)

-- | Make a mutable copy of a mutable array.
clone
:: forall h a
. STArray h a
-> ST h (STArray h a)
clone = runSTFn1 cloneImpl

foreign import cloneImpl :: forall h a. STFn1 (STArray h a) h (STArray h a)

-- | Sort a mutable array in place. Sorting is stable: the order of equal
-- | elements is preserved.
sort :: forall a h. Ord a => STArray h a -> ST h (STArray h a)
Expand Down
8 changes: 8 additions & 0 deletions test/Test/Data/Array/ST.purs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ testArrayST = do
arr <- STA.thaw [1, 2, 3]
STA.freeze arr) == [1, 2, 3]

log "clone should produce a shallow copy of an STArray"

assert $ ST.run (do
arr <- STA.thaw [1, 2, 3]
arr2 <- STA.clone arr
_ <- STA.poke 0 4 arr
STA.freeze arr2) == [1, 2, 3]

log "unsafeThaw should produce an STArray from a standard array"

assert $ STA.run (STA.unsafeThaw [1, 2, 3]) == [1, 2, 3]
Expand Down

0 comments on commit d521e17

Please sign in to comment.