[Haskell-cafe] C binding <-> safer haskell API
Viktor Dukhovni
ietf-dane at dukhovni.org
Wed Feb 9 19:33:00 UTC 2022
On Wed, Feb 09, 2022 at 06:43:39PM +0100, PICCA Frederic-Emmanuel wrote:
> So I create a binding with binding-DSL
>
> #ccall merge, Ptr <HklCube> -> Ptr <HklFrame> -> IO ()
>
> Now I want to create a higher level API which encode the fact that
> the cube is modified after the merge. So what is the best way to
> encode this in the type?
Perhaps your use-case is somewhat analogous to ByteString, which wraps
an underlying (potentially) mutable memory block as an abstract "pure"
octet string.
With ByteString, operations that produce new bytestrings do so by
copying the original buffer (except for "slices" which simply
alias part of the buffer content).
> merge :: _
> merge c f = do
> ....
> c'merge pc pf
>
> I thought about IORef, but I am not sure thaht this is the right way
> to have a safer haskell interface for this method.
Thus the wrapper function would instead have a signature of:
merge :: Cube -> Frame -> Cube
producing a new Cube, leaving the original unmodified.
If however always copying the cube is too expensive, then you can take
an approach similar to that used in Array or Vector, where Cubes are
available in both immutable and mutable forms, with freeze, thaw,
unsafeFreeze and unsafeThaw operations connecting the two.
data Cube = Cube ...
data STCube s = STCube s ...
data IOCube = IOCube ...
Mutable cubes can be modified in place in either the IO or ST Monads.
--
VIktor.
More information about the Haskell-Cafe
mailing list