为什么这种类型变量模糊? [英] Why is this type variable ambiguous?

查看:118
本文介绍了为什么这种类型变量模糊?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Cabbage.hs:

 模块Cabbage其中
类Cabbage a
其中foo :: a - >字符串 - 参数仅存在于其类型中,
- 参数值将被忽略
bar :: String - > a
quux :: Cabbage a =>字符串 - > a
quux s = bar(s ++ foo(undefined :: a))

当我编译时(使用ghc),我得到这个错误信息:

  Cabbage.hs:7:19:
模棱两可在约束中使用类型变量`a':
在Cabbage.hs:7:19-38处使用`foo'引起的Cabbage a'
可能的修复:添加修复这些类型的类型签名变量

我不明白为什么 a 不明确。第7行中的 a 肯定与第6行中的 a 相同?如何解决这个问题?



另外,是否有更好的方法来声明每个实例的常量?

undefined :: a 应该是相同的(否则 a 只是 forall a。a 的缩写。

  { - #LANGUAGE ScopedTypeVariables# - } 
模块白菜其中
类白菜a
其中foo :: a - >字符串 - 参数仅存在于其类型中,
- 参数值将被忽略
bar :: String - > a
quux :: forall a。卷心菜a =>字符串 - > a
quux s = bar(s ++ foo(undefined :: a))


Cabbage.hs:

module Cabbage where 
class Cabbage a
  where foo :: a -> String      -- the parameter is only present for its type,
                                -- the parameter value will be ignored
        bar :: String -> a
quux :: Cabbage a => String -> a
quux s = bar (s ++ foo (undefined :: a))

When I compile (with ghc) I get this error message:

Cabbage.hs:7:19:
    Ambiguous type variable `a' in the constraint:
      `Cabbage a' arising from a use of `foo' at Cabbage.hs:7:19-38
    Probable fix: add a type signature that fixes these type variable(s)

I don't understand why a is ambiguous. Surely the a in line 7 is the same as the a in line 6? How do I fix this?

Alternatively, is there a better way of declaring a per-instance constant?

解决方案

Using scoped type variables you can let GHC know that the undefined :: a should be the same (otherwise a is just a shorthand for forall a. a). Scoped type variables must then be explicitly forall-qualified:

{-# LANGUAGE ScopedTypeVariables #-}
module Cabbage where 
class Cabbage a
  where foo :: a -> String      -- the parameter is only present for its type,
                                -- the parameter value will be ignored
        bar :: String -> a
quux :: forall a. Cabbage a => String -> a
quux s = bar (s ++ foo (undefined :: a))

这篇关于为什么这种类型变量模糊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆