How to ensure optimization for large immutable vectors to be shared w.r.t. Referential Transparency
YueCompl
compl.yue at icloud.com
Tue Apr 6 11:12:51 UTC 2021
Hello Cafe and respected GHC Devs,
I would like to ensure some immutable vectors (can be quite large) are always shared instead of copied, and I think that should be straight forward w.r.t. referential transparency we enjoy.
In an attempt to determine whether two immutable vectors can be treated as the same one to enable specific optimizations for that case, I tried to use ST to determine their respective backing foreign ptrs for comparison. But appears it can be copied when wrapped in a newtype, I wonder why it is the case, and how to avoid the copy?
Here's my minimum reproducible snippet:
```hs
λ> :set -XBangPatterns
λ>
λ> :set -package vector
package flags have changed, resetting and loading new packages...
λ>
λ> import Prelude
λ>
λ> import Control.Monad.ST
λ> import qualified Data.Vector.Storable as VS
λ>
λ> :{
λ|
λ| newtype SomeVector = SomeVector (VS.Vector Int)
λ|
λ| isSameVector :: SomeVector -> SomeVector -> Bool
λ| isSameVector (SomeVector !x) (SomeVector !y) = runST $ do
λ| mx@(VS.MVector !x'offset !x'fp) <- VS.unsafeThaw x
λ| my@(VS.MVector !y'offset !y'fp) <- VS.unsafeThaw y
λ| _ <- VS.unsafeFreeze mx
λ| _ <- VS.unsafeFreeze my
λ| return $ x'offset == y'offset && x'fp == y'fp
λ|
λ| :}
λ>
λ> let !v = VS.fromList [3,2,5] in isSameVector (SomeVector v) (SomeVector v)
False
λ>
λ> let !v = SomeVector (VS.fromList [3,2,5]) in isSameVector v v
True
λ>
```
Thanks with best regards,
Compl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/ghc-devs/attachments/20210406/d5d751cc/attachment.html>
More information about the ghc-devs
mailing list