haskell - 为什么返回 String 不能算作 Show x 类型的表达式?
问题描述
谁能帮我理解为什么这段代码会产生编译错误?
hello :: (Show x) => x
hello = "Hello"
我认为String
具有 的属性Show
,所以该函数应该能够返回一个String
? 这是错误消息:
• Couldn't match expected type ‘x’ with actual type ‘[Char]’
‘x’ is a rigid type variable bound by
the type signature for:
hello :: forall x. Show x => x
at script.hs:160:1-25
• In the expression: "Hello"
In an equation for ‘hello’: hello = "Hello"
• Relevant bindings include
hello :: x (bound at script.hs:161:1)
解决方案
您的类型签名并不意味着您认为它意味着什么。
从您的解释来看,您似乎读到了这个签名,例如“我将向您返回一个x
具有Show
.将有一个“实例Show
”
但它真正的意思是“选择一个类型,任何类型,只要确保它有一个 的实例Show
,我保证我会给你返回那个类型的值”
换句话说,当一个函数是泛型时,选择泛型类型是函数的调用者,而不是实现者。
推荐阅读
- python - 通过不同列的重复值之间的条件
- java - 如何:在重新绘制之前清除 JPanel 并运行另一个类并移动对象
- android - 有什么方法可以“帮助”移动设备操作系统从 SMS 中检测代码?
- salesforce - 在 Salesforce 中将 Azure AD B2C 配置为身份验证提供程序
- javascript - 无论如何,mongodb每个月都会自动创建一个新数据库吗?
- c++ - 使用集合测试关系的对称性
- javascript - 嵌套反应路由器兄弟
- sql - 在 SQL Server 中联接表时的条件条件
- arrays - 向前和向后循环数组
- android - Android Studio & Kotlin:未解决的参考:上下文