Jacques Carette wrote:
Bulat Ziganshin wrote:

malloc :: Storable a => IO (Ptr a)
malloc  = doMalloc undefined
 where
   doMalloc       :: Storable b => b -> IO (Ptr b)
   doMalloc dummy  = mallocBytes (sizeOf dummy)


Is there any reason to not code this as

malloc :: Storable a => IO (Ptr a)
malloc  = mallocBytes $ sizeof undefined
?

Yes. The supreme clevernesss of Bulat's trick is that doMalloc unifies the type variable 'a' with the type of the argument to sizeOf, whereas "sizeOf undefined" would be ambiguous because the type of "undefined" is not constrained there ie:

 malloc :: Storable a => IO (Ptr a)
 malloc  = doMalloc undefined
   where
     doMalloc       :: Storable b => b -> IO (Ptr b)
     doMalloc dummy  = mallocBytes (sizeOf dummy)

 (doMalloc undefined) :: IO (Ptr a)

==>

 (doMalloc dummy) :: IO (Ptr a)

==>  -- doMalloc :: Storable b => b -> IO (Ptr b)

 dummy :: a

whereas:

 malloc  = mallocBytes $ sizeOf undefined

 malloc :: IO (Ptr a)

==>

 (mallocBytes (sizeOf undefined)) :: IO (Ptr a)

==>

 (sizeOf undefined) :: Int

==>

 undefined :: unconstrained

Regards, Brian.
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to