【发布时间】:2021-03-28 17:12:15
【问题描述】:
谁能帮我理解为什么这段代码会产生编译错误?
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)
【问题讨论】:
-
你想完成什么?打印消息?将字符串转换为任何
Show类型?将任何Show类型转换为字符串? -
"Hello"是一个字符串。通过使用签名Show x => x,您承诺对于作为Show类型类成员的anyx,您的函数将产生一个值,但该承诺不成立,因为您只有在x ~ String时才这样做。 -
@Aplet123 我只是在玩泛型类型签名,并没有尝试转换任何东西。我唯一的目标是让它编译 :) 但我误解了泛型类型签名在 Haskell 中的实际含义。现在已经清理干净了。
标签: haskell