[英]Haskell: Types don't match
I just tried to write a simple function to calculate the average of the input-Ints: 我只是试着写一个简单的函数来计算输入Ints的平均值:
avg :: Int -> Int -> Int -> Float
avg x y z = (x+y+z)/3
When I exchange the signature to 当我交换签名时
avg :: Float -> Float -> Float -> Float
it works fine, but with the one above I get the following error message: 它工作正常,但有了上面的一个我得到以下错误信息:
Couldn't match expected type 'Float' with actual type 'Int'. 无法将预期类型'Float'与实际类型'Int'匹配。
Which possibilites do I have to use the first signature, which accepts Ints (only)? 我有哪些可能使用第一个签名,它接受Ints(仅限)?
Use fromIntegral
to convert the Int
s to Float
s: 使用
fromIntegral
将Int
转换为Float
:
avg :: Int -> Int -> Int -> Float
avg x y z = (fromIntegral x + fromIntegral y + fromIntegral z) / 3
Shorter: 短:
avg :: Int -> Int -> Int -> Float
avg x y z = (fromIntegral $ sum [x,y,z]) / 3.0
Or you generalize this for a list of Int
s: 或者您将此概括为
Int
的列表:
avg :: [Int] -> Float
avg xs = (fromIntegral $ sum xs) / (fromIntegral $ length xs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.