[Haskell-beginners] Re: Why is this type ambiguous?

Maurí­cio CA mauricio.antunes at gmail.com
Mon Oct 26 19:12:15 EDT 2009


 > I have no idea what you're trying to do here (looks as if you
 > just want to recreate Unsafe.Coerce.unsafeCoerce?)

Yes, except that it works with Storables only and is safe against
runtime corruption. Evil, but can save you from worst FFI hacks.

 > However, dummy is first used an 'a' and then as a 'b', so that
 > can't work.

Where is dummy used as 'a'? The only place with a specific type I
used it is in 'return dummy', and it's there exactly to "get" that
'b' type.

 > Although the compiler can infer that sizeOf undefined must be of
 > the same type as sizeOf v, (...)
 >
 >    size = max (sizeOf v) (sizeOf $ undefined `asTypeOf` v)

No, it's not the same type! The idea is that 'size' value should
be the bigger of 'a' and 'b' sizes, so that I guarantee enough
memory will be allocated for the cast.

 > But... feels insanely hacky, and is not something a beginner
 > should attempt to play with I guess ;)

I have an unusual experience with Haskell. I used it a lot, but
mainly with FFI. So, I'm an expert in FFI -- I have my own package
of hsc2hs macros :) -- but I have no understanding of the type
system, except for just the basics.

Maurício

>> import Foreign
>> import Foreign.C
>>
>> genericCast :: (Storable a, Storable b) => a -> IO b
>> genericCast v = let
>>    dummy = undefined
>>    size = max (sizeOf v) (sizeOf dummy)
>>  in if False
>>    then return dummy
>>    else allocaBytes size $ \p -> poke p v >> peek (castPtr p)
>>



More information about the Beginners mailing list