ScopedTypeVariables不会将类型变量带入范围

Cli*_*ton 7 haskell ghc type-variables

这是一个返回指针对齐的简单函数:

{-# LANGUAGE ScopedTypeVariables #-}

import Foreign.Ptr (Ptr)
import Foreign.Storable (Storable, alignment)

main = return ()

ptrAlign1 :: (Storable a) => Ptr a -> Int
ptrAlign1 _ = alignment (undefined :: a) 
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

如果我ptrAlign像这样重写一个更混乱的派系:

ptrAlign2 :: (Storable a) => Ptr a -> Int
ptrAlign2 = ptrAlign3 undefined where
  ptrAlign3 :: (Storable a) => a -> Ptr a -> Int
  ptrAlign3 x _ = alignment x
Run Code Online (Sandbox Code Playgroud)

它工作正常(当然这个版本甚至不需要ScopedTypeVariables).

但我仍然很好奇为什么第一个版本会抛出错误,以及可以采取哪些措施来解决它?

Cac*_*tus 10

即使ScopedTypeVariables打开,类型变量也不会放在范围内,除非您明确量化它们,即

ptrAlign1 :: forall a. (Storable a) => Ptr a -> Int
ptrAlign1 _ = alignment (undefined :: a) 
Run Code Online (Sandbox Code Playgroud)