将数据表示为字符串

时间:2013-08-08 01:44:11

标签: haskell

我有以下简单的代码:

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

1 个答案:

答案 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