Double -> non-double function :)

Jay Cox [email protected]
Wed, 3 Apr 2002 21:32:14 -0600 (CST)


On Wed, 3 Apr 2002, Hal Daume III wrote:

> I found one way:
>
> doubleToInts d = runST (
>     do arr <- newDoubleArray (1,2)
>        writeDoubleArray arr 1 d
>        i1 <- readIntArray arr 1
>        i2 <- readIntArray arr 2
>        return (i1,i2))
>
> intsToDouble (i1,i2) = runST (
>     do arr <- newDoubleArray (1,2)
>        writeIntArray arr 1 i1
>        writeIntArray arr 2 i2
>        readDoubleArray arr 1)
>
> But this is dumb and very slow (also note that the array has to be indexed
> to 2 even though it's only storing one double; this is because
> readIntArray checks the double bounds).
>
> Ideas *other* than this are still welcome :)



ghc has some things that are useful for marshalling values between C and
haskell you might want to look at.  MarshalAlloc, Storable, Ptr, etc. I
haven't looked at it much, but it does apparently have things for what you
want.  It looks like you could cast a Ptr Double to a Ptr Int, and poke at
it, etc.  It seems, though, that its all restricted to the IO monad, so,
perhaps there might be an actual valid use for unsafeperformIO in here
with this.


<the code I loaded prior to "messing around" with ghci -package lang
file.lhs>


>import Storable
>import MarshalAlloc
>import Ptr
>
>main = print "hello"


<reformatted to make more readable by humans.>


Main> do x<-(malloc::IO (Ptr Double));
         poke x 3;
         y<-peek x;
         let z=(castPtr x)::Ptr Int in
         do poke z 1024;
            z'<-peek x;
            print (y,z')



<result>

(3.0,3.0000000000004547)


Cheers,


Jay Cox