不能在另一个定义中使用实例方法实现
Can not use instance method implementation inside another definition
你好,我不明白为什么我会遇到以下问题:
我正在尝试使用 Employee
中的 taxes
实现来定义 Company
的 taxes
定义。我不明白为什么我会遇到以下错误:
data Employee=Employee{
age::Int,
name::String,
job::Job,
wage::Double
}
data Job= Worker | Manager |Unemployed deriving(Eq,Ord,Show)
data Company=Company{
compName::String,
year::Int,
employees::[Employee]
}
class Charges a where
taxes::a->Double
instance Charges Employee where
taxes Employee{age=a,wage=w}=fromIntegral a * w
实施 1:
instance Charges Company where
taxes comp=foldl ((+).taxes) 0 employees
错误:
Couldn't match type `[Employee]' with `Double'
Expected type: Company -> Double
Actual type: Company -> [Employee]
为什么这是一个问题,因为我一个一个地应用 Employee
,我应用 taxes
,它已经为 Employee
实现,我将它添加到计数器??
实施 2 - 使用 foldr
instance Charges Company where
taxes comp =foldl ((+).taxes) 0 (employees comp)
错误:
Couldn't match expected type `Company -> Double'
with actual type `Double'
* Possible cause: `foldr' is applied to too many arguments
我只看到 3 个参数,有什么问题吗?
Prelude 中已经有一个非常适合对数字列表求和的函数。为什么我们要用折叠重塑求和?将问题分解为几个部分:
- 查找公司员工
- 计算每个税金
- 对结果求和
因此:
instance Charges Company where
taxes = sum . map taxes . employees
你好,我不明白为什么我会遇到以下问题:
我正在尝试使用 Employee
中的 taxes
实现来定义 Company
的 taxes
定义。我不明白为什么我会遇到以下错误:
data Employee=Employee{
age::Int,
name::String,
job::Job,
wage::Double
}
data Job= Worker | Manager |Unemployed deriving(Eq,Ord,Show)
data Company=Company{
compName::String,
year::Int,
employees::[Employee]
}
class Charges a where
taxes::a->Double
instance Charges Employee where
taxes Employee{age=a,wage=w}=fromIntegral a * w
实施 1:
instance Charges Company where
taxes comp=foldl ((+).taxes) 0 employees
错误:
Couldn't match type `[Employee]' with `Double'
Expected type: Company -> Double
Actual type: Company -> [Employee]
为什么这是一个问题,因为我一个一个地应用 Employee
,我应用 taxes
,它已经为 Employee
实现,我将它添加到计数器??
实施 2 - 使用 foldr
instance Charges Company where
taxes comp =foldl ((+).taxes) 0 (employees comp)
错误:
Couldn't match expected type `Company -> Double'
with actual type `Double'
* Possible cause: `foldr' is applied to too many arguments
我只看到 3 个参数,有什么问题吗?
Prelude 中已经有一个非常适合对数字列表求和的函数。为什么我们要用折叠重塑求和?将问题分解为几个部分:
- 查找公司员工
- 计算每个税金
- 对结果求和
因此:
instance Charges Company where
taxes = sum . map taxes . employees