首页 > 解决方案 > 为什么返回 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)

标签: haskell

解决方案


您的类型签名并不意味着您认为它意味着什么。

从您的解释来看,您似乎读到了这个签名,例如“我将向您返回一个x具有Show.将有一个“实例Show

但它真正的意思是“选择一个类型,任何类型,只要确保它有一个 的实例Show,我保证我会给你返回那个类型的值

换句话说,当一个函数是泛型时,选择泛型类型是函数的调用者,而不是实现者。


推荐阅读