gpt4 book ai didi

Haskell zipWith

转载 作者:行者123 更新时间:2023-12-04 14:08:20 27 4
gpt4 key购买 nike

我想总结一个压缩列表。

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

当我去 ghci 并执行以下操作时:
sum(zipWith (*) [0.75, 0.25] [6, 4])

我得到了我想要的。

但是在代码中我遇到了一个错误,我不知道为什么。
    averageGrade :: [Float] -> [Int] -> Float
averageGrade a b
| a == [] = 0
| b == [] = 0
| otherwise = (sum(zipWith (*) a b))

如果我想编译它,我会遇到以下失败:
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.

最佳答案

你不能*两个不同类型的数字,如 FloatInt .您需要显式转换其中一个,以便它们具有相同的类型(在您的情况下为 Float)。

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

请注意,您实际上并不需要检查 ==[]案例,自 zipWith返回 []是那些情况, sum [] == 0 .
averageGrade :: [Float] -> [Int] -> Float
averageGrade a b = sum (zipWith (\ x y -> x * fromIntegral y) a b)

关于Haskell zipWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58853038/

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