在Haskell中使用词典作用域类型变量分析错误
当我向GHC提交代码时在Haskell中使用词典作用域类型变量分析错误,haskell,parse-error,type-variables,Haskell,Parse Error,Type Variables,当我向GHC提交代码时 {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, ScopedTypeVariables #-} class Modular s a | s -> a where modulus :: s -> a newtype M s a = M {unM :: a} deriving (Eq, Show) normalize :: (Modular s a, Integral a) =
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, ScopedTypeVariables #-}
class Modular s a | s -> a where modulus :: s -> a
newtype M s a = M {unM :: a} deriving (Eq, Show)
normalize :: (Modular s a, Integral a) => a -> M s a
normalize x :: M s a = M (x `mod` (modulus (undefined :: s)))
我得到以下错误:
config1.hs:10:1: Parse error in pattern: normalize
你能帮忙吗
埃里克·麦考利
normalize x :: M s a = -- ...
这是错误的。没有理由像这样在定义中声明返回类型,您已经在前一行的类型签名中声明了它。事实上,它在语法上是无效的,这就是为什么会出现解析错误的原因
但是,一旦修复了解析错误(通过删除::msa
),它仍然无法工作,因为您还没有实际使用作用域类型变量:
为了使用作用域类型变量扩展,需要使用forall
关键字显式声明类型变量。固定定义如下所示:
normalize :: forall s a. (Modular s a, Integral a) => a -> M s a
normalize x = M (x `mod` (modulus (undefined :: s)))
这是错误的。没有理由像这样在定义中声明返回类型,您已经在前一行的类型签名中声明了它。事实上,它在语法上是无效的,这就是为什么会出现解析错误的原因
但是,一旦修复了解析错误(通过删除::msa
),它仍然无法工作,因为您还没有实际使用作用域类型变量:
为了使用作用域类型变量扩展,需要使用forall
关键字显式声明类型变量。固定定义如下所示:
normalize :: forall s a. (Modular s a, Integral a) => a -> M s a
normalize x = M (x `mod` (modulus (undefined :: s)))
我想你想要的是:
normalize :: forall s a . (Modular s a, Integral a) => a -> M s a
normalize x = M (x `mod` (modulus (undefined :: s)))
请注意,当您使用ScopedTypeVariables
语言功能时,所有s a.的将类型变量s
和a
带入函数体的作用域
GHC从未支持您尝试的语法 我想你想要的是:
normalize :: forall s a . (Modular s a, Integral a) => a -> M s a
normalize x = M (x `mod` (modulus (undefined :: s)))
请注意,当您使用ScopedTypeVariables
语言功能时,所有s a.
的将类型变量s
和a
带入函数体的作用域
GHC从未支持您尝试的语法