当前位置:  开发笔记 > 小程序 > 正文

Haskell:使用sizeOf时Storable中的模糊类型变量

如何解决《Haskell:使用sizeOf时Storable中的模糊类型变量》经验,为你挑选了1个好方法。

汇编

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 ....有没有办法在没有伪论证的情况下解决歧义?



1> leftaroundab..:

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)
     ...


@myrix是的,这是正确的.扩展只允许为每个要在功能体上作用域的类型变量添加forall abc ....
推荐阅读
罗文彬2502852027
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有