Haskell自定义样式实例显示带有列表的数据类型

时间:2017-11-18 14:28:17

标签: haskell

我正在尝试使用以下结构为我的数据类型Family创建一个实例Show:

x
  y1
  y2
  y3

我想出了这个:

import Data.List

data Family = Family {x :: String, y :: [[Char]]} deriving (Eq,Read)

-- this function prints the y in a new line with two spaces before
printY ys = putStrLn(foldr (++) "" (map (\str -> "  " ++ str ++ "\n") ys))

instance Show Family where
    show x = show x ++ "\n"
    show y = show printY y

但是我收到了这个错误:

* Couldn't match expected type `Family -> String'
                  with actual type `[Char]'
    * The function `show' is applied to two arguments,
      but its type `([[Char]] -> IO ()) -> [Char]' has only one
      In the expression: show printme descendentes
      In an equation for `show':
          show descendentes = show printme descendentes
   |
22 |         show y = show printY y

我怎么能解决这个问题并获得我需要的演出风格?

2 个答案:

答案 0 :(得分:1)

xy不是Family个构造函数。您似乎正在尝试在Family的字段上进行模式匹配,但您无法根据自己设置的方式进行匹配。

我认为你想要的是:

instance Show Family where
    show (Family x y) = (show x) ++ "\n" ++ (printY y)

但请注意,您的printY功能已被打破"。尝试为它编写类型签名。问题是,你在函数中打印,这违背了将对象转换为String的目标,这是show应该做的事情。将printY更改为showY,然后移除对putStrLn的调用。

答案 1 :(得分:0)

Show类型类定义的show类型是:

forall a. Show a => a -> String

对于您的家庭类型,它将专注于:

Show Family => Family -> String

您需要定义实例以匹配上述类型:

instance Show Family where
  show (Family x ys) = ...

并确保返回一个字符串。