【问题标题】:Haskell - Show instance multiple datatypesHaskell - 显示实例多种数据类型
【发布时间】:2012-10-06 17:05:12
【问题描述】:

我目前正在为学校作业制作国际象棋游戏,并且我的棋子已定义

    data Piece = Piece { piecetype :: PieceType, color :: PieceColor }
    data PieceType = Pawn | Knight | Bishop | Rook | Queen | King
    data PieceColor = Black | White deriving Eq

现在我必须将一块作为单个字符(king = k,queen = q,knight = n 等)打印为黑色块,其值是其白色值的大写(king = K,queen = Q , 骑士 = N 等) 所以我做了三个 show 实例

    instance Show PieceColor where
        show Black = "B"
        show White = "W"

    instance Show PieceType where
        show Pawn = "P"
        show Knight = "N"
        show Bishop = "B"
        show Rook = "R"
        show Queen = "Q"
        show King = "K"

第三个是问题

    instance Show Piece where
        show (piecetype, color) = show piecetype 
                                  if show color == "W"
                                  then show piecetype
                                  else toUpper (show piecetype)

我收到以下错误(我也尝试了很多,但根据此链接,我似乎非常接近 Something somewhat similar

Couldn't match expected type `Piece' with actual type `(t0, t1)'

感谢任何帮助 亲切的问候,我

【问题讨论】:

  • 应该是show (Piece piecetype color) 而不是show (piecetype,color)。
  • 我的一些错误,它就像一个魅力,感谢 Satvik

标签: haskell types instance show


【解决方案1】:

直接回答:

instance Show Piece where
    show (Piece piecetype Black) = map toLower $ show piecetype
    show (Piece piecetype White) = show piecetype

解释:

  • Piece 是具有构造函数 Piece 的数据类型(类型名称和构造函数都与您的情况相同),而不是元组。所以你应该在构造函数而不是元组上进行模式匹配。

  • toUpper 和 toLower 出现在 Data.Char 中并在 Char 上工作,而像 "B" 这样的东西是 String(String 是 [Char] 的类型同义词)。所以要将String 设为大写,您可以使用map toUpper。

  • 比较像show color == "B" 这样的字符串效率不高,您可以在构造函数名称上使用模式匹配。

【讨论】:

  • 我还建议直接在颜色上进行模式匹配,而不是 if show color == "B" ...
猜你喜欢
  • 2016-09-20
  • 2017-01-14
  • 2016-08-12
  • 1970-01-01
  • 2013-08-14
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多