haskell - ScopedTypeVariables 不会将类型变量带入作用域

标签 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) 

但我收到以下错误:

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) 

关于haskell - ScopedTypeVariables 不会将类型变量带入作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34012115/

相关文章:

Haskell 和 Vim : Proper Indentation

list - ghci 如何为类型变量选择名称?

generics - Swift 通用类型变量应遵守协议(protocol)(类型类)

list - 使用 Int 列表删除列表中的元素(Haskell)

haskell - 什么是 AllowAmbiguousTypes,为什么在这个 "forall"示例中需要它?

haskell - 没有方法的类型类,用作约束 : do they get dictionaries?

haskell - 在 Haskell 中将两个类合并/合并为一个类

haskell - Haskell 在完整性检查中缺少什么?

java - 如何在 Frege 中声明带有类型变量的 native 接口(interface)?

generics - 为什么编译器会将两个具有不同名称的等效签名的泛型类型变量识别为不同类型?