Search code examples
haskellfold

Can not use instance method implementation inside another definition


Hello i do not understand why i do have the following problem : I am trying to define taxes definition for Company using taxes implementation from Employee.I do not understand why i face the following errors:

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

Implementation 1:

instance Charges Company where 
    taxes comp=foldl ((+).taxes) 0 employees  

Error:

Couldn't match type `[Employee]' with `Double'
  Expected type: Company -> Double
    Actual type: Company -> [Employee]

Why is it a problem since i take an Employee one by one i apply taxes which is already implemented for Employee and i add it to the counter??

Implementation2 - using foldr

 instance Charges Company where 
        taxes comp =foldl ((+).taxes) 0 (employees comp)

Error:

Couldn't match expected type `Company -> Double'
                  with actual type `Double'
    * Possible cause: `foldr' is applied to too many arguments

I see no more then 3 arguments what is the problem?


Solution

  • There is already a function in the Prelude that is excellent for summing lists of numbers. Why are we reinventing summation with a fold? Break the problem down into a few parts:

    • Find the company's employees
    • Compute taxes for each
    • Sum the results

    Thus:

    instance Charges Company where 
        taxes = sum . map taxes . employees