Eri*_*ric 1 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) => a -> M s a
normalize x :: M s a = M (x `mod` (modulus (undefined :: s)))
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
config1.hs:10:1: Parse error in pattern: normalize
Run Code Online (Sandbox Code Playgroud)
你能帮我吗?
Eric Macaulay
normalize x :: M s a = -- ...
Run Code Online (Sandbox Code Playgroud)
这是错的.没有理由在这样的定义中声明返回类型,你已经在之前的行中的类型签名中声明了它.事实上,它在语法上是无效的,并且是你得到解析错误的原因.
但是,一旦你修复了解析错误(通过删除:: M s a),它仍然无法工作,因为你还没有实际使用范围类型变量:
为了使用范围类型变量扩展,您需要使用forall关键字显式声明类型变量.固定定义如下所示:
normalize :: forall s a. (Modular s a, Integral a) => a -> M s a
normalize x = M (x `mod` (modulus (undefined :: s)))
Run Code Online (Sandbox Code Playgroud)