【问题标题】:Parse error using lexically scoped type variables in Haskell在 Haskell 中使用词法范围的类型变量解析错误
【发布时间】:2011-08-19 12:14:51
【问题描述】:

当我向 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)))

我收到以下错误:

config1.hs:10:1: Parse error in pattern: normalize

你能帮忙吗?

埃里克·麦考利

【问题讨论】:

    标签: haskell parse-error type-variables


    【解决方案1】:
    normalize x :: M s a = -- ...
    

    这是错误的。没有理由像这样在定义中声明返回类型,您已经在之前行的类型签名中声明了它。事实上,它在语法上是无效的,也是您收到解析错误的原因。

    但是,一旦您修复了解析错误(通过删除 :: 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)))
    

    【讨论】:

      【解决方案2】:

      我想你想要的是这样的:

      normalize :: forall s a . (Modular s a, Integral a) => a -> M s a
      normalize x = M (x `mod` (modulus (undefined :: s)))
      

      注意forall s a.,当您使用ScopedTypeVariables 语言功能时,它会将类型变量sa 带入函数体的范围内。

      GHC 从未支持您尝试的语法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-08
        • 1970-01-01
        相关资源
        最近更新 更多