gpt4 book ai didi

haskell - 如何比较haskell中的自定义数据类型

转载 作者:行者123 更新时间:2023-12-01 08:21:45 24 4
gpt4 key购买 nike

我有一个想要比较的自定义数据类型。

data Tile = Wall | Ground | Storage | Box | Blank

我想做instance-of-tile == Box

我试过像这样使用 ==

tileToInteger :: Tile -> Integer
tileToInteger tile
| tile == Blank || tile == Wall = 1
| otherwise = 2

我也试过

tileToInteger :: Eq => Tile -> Integer

stack build 的错误信息是

No instance for (Eq Tile) arising from a use of ‘==’
• In the first argument of ‘(||)’, namely ‘tile == Blank’
In the expression: tile == Blank || tile == Wall
In a stmt of a pattern guard for an equation for ‘tileToInteger’: tile == Blank || tile == Wall

这是完整的示例代码

data Tile = Wall | Ground | Storage | Box | Blank

getTileAtXY :: Integer -> Integer -> Tile
getTileAtXY x y
| x == 0 && y == 0 = Box
| otherwise = Ground

tileToInteger :: Tile -> Integer
tileToInteger tile
| tile == Blank || tile == Wall = 1
| otherwise = 2

main :: IO ()
main = print (tileToInteger (getTileAtXY 1 0))

背景

最佳答案

错误

No instance for (Eq Tile) arising from a use of ‘==’

表示您将 (==) 与两个 Tile 一起使用,但编译器没有找到 Eq Tile 的实例,其中您为 Tiles 定义了 (==) 函数。

您可以将其设为 Eq typeclass 的实例:

data Tile = Wall | Ground | Storage | Box | Blank <b>deriving Eq</b>

如果你自动派生 Eq,那么 Haskell 认为 Tile 的两个对象在给定数据构造函数(WallGround, ...) 是相同的,并且它们的所有参数都是相同的。由于 Tile 数据类型的数据构造函数没有参数,因此这仅意味着 Wall 等于 Wall, Ground 等于 Ground 等。

但是,在您的函数 tileToInteger 中,您根本不需要 使用 (==),您可以使用 pattern matching [Haskell-wiki] ,比如:

tileToInteger :: Tile -> Integer
tileToInteger <b>Blank</b> = 1
tileToInteger <b>Wall</b> = 1
tileToInteger <b>_</b> = 2

您可以通过模式匹配为 Tile 实现 (==) 函数,例如:

instance Eq Tile where
Wall == Wall = True
Ground == Ground = True
Storage == Storage = True
Box == Box = True
Blank == Blank = True
_ == _ = False

然而,上面的内容等价于 deriving Eq 将执行的操作,因此通常只有在两个 Tile 被认为是等价的情况下才手动实现 Eq以不同的方式。

关于haskell - 如何比较haskell中的自定义数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56406701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com