汇编
byte_list_to_storable :: Storable a => [CUChar] -> MaybeT IO a byte_list_to_storable byte_list = do let size_of_storable = sizeOf (undefined :: a) when (length byte_list /= size_of_storable) mzero liftIO . alloca $ \pointer -> do forM (zip [0 .. size_of_storable - 1] byte_list) (\(index, byte) -> pokeByteOff pointer index byte) peek pointer
失败了
Ambiguous type variable `a0' in the constraint: (Storable a0) arising from a use of `sizeOf' Probable fix: add a type signature that fixes these type variable(s) In the expression: sizeOf (undefined :: a) In an equation for `size_of_storable': size_of_storable = sizeOf (undefined :: a) In the expression: do { let size_of_storable = sizeOf (undefined :: a); when (length byte_list /= size_of_storable) mzero; liftIO . alloca $ \ pointer -> do { ... } }
尽管显式类型注释.它可以用伪参数修复:
byte_list_to_storable :: Storable a => a -> [CUChar] -> MaybeT IO a byte_list_to_storable dummy byte_list = do let size_of_storable = sizeOf dummy
但是byte_list_to_storable
必须一直这样称呼byte_list_to_storable undefined ...
.有没有办法在没有伪论证的情况下解决歧义?
a
默认情况下,Haskell类型变量(如您的变量)仅存在于一个特定类型的签名中.当你sizeOf (undefined :: a)
进一步向下写时,在函数定义中,GHC不a
以任何方式将其与in中的相关联MaybeT IO a
,而是将其解释为一个全新且无约束的类型变量.
改变这种情况的方法是打开ScopedTypeVariables
:
{-# LANGUAGE ScopedTypeVariables #-} byteListToStorable :: forall a . Storable a => [CUChar] -> MaybeT IO a byteListToStorable bytelist = do let sizeOfStorable = sizeOf (undefined :: a) ...