haskellghcizipwith

Haskell zipWith


I want to sum a zipped list.

averageGrade :: [Float] -> [Int] -> Float
averageGrade [0.75 , 0.25] [6, 4] , result: 0,75*6 + 0.25*4 = 5.5 

when I go to ghci and do the following:

sum(zipWith (*) [0.75, 0.25] [6, 4])

I get excactly what i want to.

But in code I'm getting an error, and I don't know why.

    averageGrade :: [Float] -> [Int] -> Float
    averageGrade a b
                | a == [] = 0
                | b == [] = 0
                | otherwise = (sum(zipWith (*) a b))

If I want to compile this I'm getting the following failure:

Couldn't match type ‘Int’ with ‘Float’
Expected type: [Float]
  Actual type: [Int]
In the third argument of ‘zipWith’, namely ‘b’
In the first argument of ‘sum’, namely ‘(zipWith (*) a b)’
Failed, modules loaded: none.

Solution

  • You can't * two numbers having a different type, like Float and Int. You need to explicitly convert one of them so that they have the same type (Float, in your case).

    averageGrade :: [Float] -> [Int] -> Float
    averageGrade a b
                | a == [] = 0
                | b == [] = 0
                | otherwise = sum (zipWith (\ x y -> x * fromIntegral y) a b)
    

    Note that you do not really need to check the ==[] cases, since zipWith returns [] is those cases, and sum [] == 0.

    averageGrade :: [Float] -> [Int] -> Float
    averageGrade a b = sum (zipWith (\ x y -> x * fromIntegral y) a b)