[Haskell-beginners] Why is this type ambiguous?

Peter Verswyvelen bugfact at gmail.com
Mon Oct 26 18:38:50 EDT 2009

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

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

Next, in sizeOf undefined, undefined does not provide enough
information about that type undefined should be. Although the compiler
can infer that sizeOf undefined must be of the same type as sizeOf v,
that's not enough, it needs to know the type of undefined (I guess you
want it to be the same type as v?)

Can be fixed like:

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

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

2009/10/26 Maurí­cio CA <mauricio.antunes at gmail.com>:
> 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)
> ----
> Code above gives me this:
>  Ambiguous type variable `a' in the constraint:
>    `Storable a'
>      arising from a use of `sizeOf' at src/Bindings/C.hs:28:27-38
> ----
> It seems to refer to '(sizeOf dummy)'. But isn't the
> type of 'dummy' defined by 'return dummy' beeing a
> possible return value (and, so, dummy :: b)?
> Thanks,
> Maurício
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

More information about the Beginners mailing list