gpt4 book ai didi

haskell - 具有多个子字段的数据类型的实例方程

转载 作者:行者123 更新时间:2023-12-02 12:13:49 25 4
gpt4 key购买 nike

我有一个包含多个子字段的数据类型,并且希望同时实现instance Eq类。

代码如下:

data Expression 
= Variable {
name :: String,
number :: Double,
exponentVal :: Double
}
| Numeric Double
| CanonicalForm [Expression]
deriving Show

instance Eq Expression where
someone == another = name someone == name another
someone == another = exponentVal someone == exponentVal another

如何修改 instance Eq 类,以便当我比较两个变量时,比较会同时计算 name 字段和 exponentVal 字段?

最佳答案

== 定义中使用模式匹配

instance Eq Expression where
Variable a b c == Variable a' b' c = a == a' && b == b' && c == c'
-- other 2 cases
_ == _ = False

或者只是使用导出方程,正如评论中已经指出的那样。

关于haskell - 具有多个子字段的数据类型的实例方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59137368/

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