ScopedTypeVariables 不会将类型变量带入作用域
ScopedTypeVariables doesn't bring type variables into scope
这里有一个简单的函数来 return 指针对齐:
{-# LANGUAGE ScopedTypeVariables #-}
import Foreign.Ptr (Ptr)
import Foreign.Storable (Storable, alignment)
main = return ()
ptrAlign1 :: (Storable a) => Ptr a -> Int
ptrAlign1 _ = alignment (undefined :: a)
但我收到以下错误:
Could not deduce (Storable a0) arising from a use of `alignment'
from the context (Storable a)
bound by the type signature for
ptrAlign1 :: Storable a => Ptr a -> Int
at prog.hs:8:14-41
The type variable `a0' is ambiguous
如果我重写 ptrAlign
在一个更混乱的派系中,像这样:
ptrAlign2 :: (Storable a) => Ptr a -> Int
ptrAlign2 = ptrAlign3 undefined where
ptrAlign3 :: (Storable a) => a -> Ptr a -> Int
ptrAlign3 x _ = alignment x
很好用(当然这个版本连ScopedTypeVariables
都不需要)
但我仍然很好奇为什么第一个版本会抛出错误,以及如何解决它?
即使 ScopedTypeVariables
开启,类型变量也不会放入范围内,除非您明确量化它们,即
ptrAlign1 :: forall a. (Storable a) => Ptr a -> Int
ptrAlign1 _ = alignment (undefined :: a)
这里有一个简单的函数来 return 指针对齐:
{-# LANGUAGE ScopedTypeVariables #-}
import Foreign.Ptr (Ptr)
import Foreign.Storable (Storable, alignment)
main = return ()
ptrAlign1 :: (Storable a) => Ptr a -> Int
ptrAlign1 _ = alignment (undefined :: a)
但我收到以下错误:
Could not deduce (Storable a0) arising from a use of `alignment'
from the context (Storable a)
bound by the type signature for
ptrAlign1 :: Storable a => Ptr a -> Int
at prog.hs:8:14-41
The type variable `a0' is ambiguous
如果我重写 ptrAlign
在一个更混乱的派系中,像这样:
ptrAlign2 :: (Storable a) => Ptr a -> Int
ptrAlign2 = ptrAlign3 undefined where
ptrAlign3 :: (Storable a) => a -> Ptr a -> Int
ptrAlign3 x _ = alignment x
很好用(当然这个版本连ScopedTypeVariables
都不需要)
但我仍然很好奇为什么第一个版本会抛出错误,以及如何解决它?
即使 ScopedTypeVariables
开启,类型变量也不会放入范围内,除非您明确量化它们,即
ptrAlign1 :: forall a. (Storable a) => Ptr a -> Int
ptrAlign1 _ = alignment (undefined :: a)