无法将预期类型与推断类型匹配,刚性类型变量错误 [英] Couldn't Match Expected Type Against Inferred Type, Rigid Type Variable Error

查看:34
本文介绍了无法将预期类型与推断类型匹配,刚性类型变量错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个函数有什么问题?

test :: Show s => s
test = "asdasd"

String 是 Show 类的一个实例,所以它看起来是正确的.

String is an instance of the Show class, so it seems correct.

错误是

srcMain.hs:224:7:
    Couldn't match expected type `s' against inferred type `[Char]'
      `s' is a rigid type variable bound by
          the type signature for `test' at srcMain.hs:223:13
    In the expression: "asdasd"
    In the definition of `test': test = "asdasd"

推荐答案

test :: Foo a =>a 的意思是对于作为 Foo 实例的任何类型,test 是该类型的值".因此,在任何可以使用 X 类型的值的地方,其中 X 是一个实例 Foo,您都可以使用 类型的值>Foo a =>一个.

test :: Foo a => a means "for any type which is an instance of Foo, test is a value of that type". So in any place where you can use a value of type X where X is an instance Foo, you can use a value of type Foo a => a.

类似于 test :: Num a =>一个;test = 42 有效,因为 42 可以是 IntIntegerFloat 类型的值或任何其他类型的值数字.

Something like test :: Num a => a; test = 42 works because 42 can be a value of type Int or Integer or Float or anything else that is an instance of Num.

但是 "asdasd" 不能是 Int 或其他任何是 Show 实例的东西——它只能是一个字符串.因此,它与 Show s => 类型不匹配.s.

However "asdasd" can't be an Int or anything else that is an instance of Show - it can only ever be a String. As a consequence it does not match the type Show s => s.

这篇关于无法将预期类型与推断类型匹配,刚性类型变量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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