繁体   English   中英

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

[英]Haskell custom style instance show for Data type with list

我正在尝试为具有以下结构的数据类型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

如何解决此问题并获得所需的演出风格?

xy不是Family构造函数。 看起来您正在尝试在Family字段上进行模式匹配,但是您无法通过设置方式来做到这一点。

我认为您想要的是这样的:

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

但是请注意,您的printY函数“已损坏”。 尝试为其编写类型签名。 问题是,您要在函数中进行打印,这违背了将对象转换为String的目标,这正是show应该做的。 更改printYshowY ,并删除调用putStrLn

由显示类型类定义的显示类型为:

forall a. Show a => a -> String

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

Show Family => Family -> String

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

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

并确保返回一个字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM