在 Haskell 中打印新类型

Printing new types in Haskell

我正在按照教程创建新类型。这是我的代码:

data Shape = Circle Float Float Float | Rectangle Float Float Float Float

当我用 ghci 加载文件并键入:

Circle 10 20 5

它打印这个:

<interactive>:29:1:
    No instance for (Show Shape) arising from a use of ‘print’
    In a stmt of an interactive GHCi command: print it

我该如何解决这个问题?

show 函数的类型为:

show :: Show a => a -> String

这意味着它只适用于具有 Show 个实例的事物。您可以通过手动定义实例或让编译器自动派生一个实例来使您的类型成为 Show class 的实例:

data Shape = Circle Float Float Float | Rectangle Float Float Float Float
  deriving (Show)

instance Show Shape where
    show (Circle a b c) = "Circle " ++ show a ++ " " ++ show b ++ " " ++ show c
    show (Rectangle a b c d) = ...

我在解释器中输入以下代码解决了这个问题:

:s -u