1

我有以下简单的代码:

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在屏幕上(打印)表示我想要的任何内容。

4

1 回答 1

4

您需要添加显示:

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
于 2013-08-08T01:48:44.993 回答