它为什么抱怨这个代码:
data Point = Point {
x, y :: Int
} deriving (Show)
main = print $ Point (15 20)
通过说:
No instance for (Show (Int -> Point))
arising from a use of `print'
Possible fix: add an instance declaration for (Show (Int -> Point))
您的括号错误。将(15 20)
括起来会使编译器将其视为Point
的一个参数,而您缺少了第二个参数。如果去掉这些括号以留下Point 15 20
,它将起作用。
出了什么问题
data Point = Point {
x, y :: Int
} deriving (Show)
如果我们将构造函数Point
表示为一个函数:,这可能会变得更加明显
Point :: Int -> Int -> Point
如果你知道函数应用程序的语法,那么这就变得非常清楚了:
main = print $ Point 15 20
为什么出现此错误
至于为什么损坏的代码会导致特定的错误,请考虑如何进行类型检查。我们有一个表达式:
Point ( ...something... )
如果Point :: Int -> Int -> Point
,那么Point something
必须是Int -> Point
类型(应用于任何单个参数的Point
都具有所述类型)。现在,您可以看到它是如何得出结论的,您正试图在类型为Int -> Point
的对象上调用print
,从而抱怨缺少实例——它甚至没有考虑(15 20)
的坏表达式。