gpt4 book ai didi

Haskell - 实现和实例

转载 作者:行者123 更新时间:2023-12-03 01:36:43 25 4
gpt4 key购买 nike

如果有两种不同的数据类型,但它们具有相似的功能:

type model = String
type priceOfC = Int
data Car = Cars model priceOfC

ComparePricesCar :: Car -> Car -> Int
.... (some codes here to compare prices between two cars)

type color = String
type priceOfB = Int
data Bike = Bikes color priceOfB

ComparePricesBike :: Bike -> Bike -> Int
.... (some codes here to compare prices between two bikes)

我遇到的问题是实现一个类型类“Traffic”,并让 Car 和 Bike 成为 Traffic 的实例。所有实例都将实现一个名为“comparePrice”的函数。

我已经尝试过:

class Traffic a where
comparePrice :: a -> a -> Int

instance Traffic Car where
comparePrice (Cars a b)(Cars c d) = ComparePricesCar (Cars a b)(Cars c d)

instance Traffic Bike where
comparePrice (Bikes a b)(Bikes c d) = ComparePricesBike (Bikes a b)(Bikes c d)

它似乎无法处理我多次声明的comparePrice的错误消息。如何让代码起到问题描述的作用?任何帮助,谢谢!

最佳答案

您需要缩进类和实例定义的主体。否则,它认为正文是空的,并且comparePrice的定义应该独立于Traffic类。

关于Haskell - 实现和实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688683/

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