[Haskell-cafe] Problem trying to get class Bounded to work

Brian Hulley brianh at metamilk.com
Tue May 23 11:10:23 EDT 2006


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. 



More information about the Haskell-Cafe mailing list