我有以下简单的代码:
data Shape = Circle Float Float Float | Rectangle Float Float Float Float deriving (Show)
surface :: Shape -> Float
surface (Circle _ _ r) = pi * r ^ 2
main = putStrLn $ surface $ Circle 10 20 30
它抱怨道:
Couldn't match expected type `String' with actual type `Float'
In the second argument of `($)', namely `surface $ Circle 10 20 30'
如何摆脱错误?我还想将“show
方法”添加到Shape
并覆盖它,以便我可以在屏幕上(打印)代表Shape
。
答案 0 :(得分:4)
您需要添加show:
main = putStrLn $ show $ surface $ Circle 10 20 30
如果您想要自己的Show方法,请不要派生Show:
data Shape = Circle Float Float Float
| Rectangle Float Float Float Float
instance Show Shape where
show (Circle _ _ r) = show r
show (Rectangle r _ _ _) = show r
main = putStrLn $ show $ Circle 10 20 30