除法错误,Haskell
Error with divides, Haskell
我的代码,其中 n = 4:
f n = map (4/) [1..n]
main = do
n <- getLine
print(f (product(map read $ words n :: [Int])))
如果我在终端 map (4/) [1..n]
中使用,我会得到正确答案:[4.0,2.0,1.3333333333333333,1.0]
。
但在我的程序中它不起作用,错误消息是:No instance for (Fractional Int) arising from a use of
f'`
我的错误在哪里?
您的 n
是 Int
类型,而不是 Fractional
类型。这些是使用 /
运算符支持除法的那些。您可以将 /
替换为 div
以获得整数除法(截断为整数),或者您可以添加 fromIntegral
将 n
转换为正确的类型。
您的代码应该类似于
f n = map (4/) [1..fromIntegral n]
进一步澄清:您的函数 f 最终对提供给它的参数进行除法。这导致类型推理引擎确定那些参数应该是 Fractional
类型。然后你在你的 main
中使用那个函数,你明确地给它一个 Int
。
这就是错误显示 "You gave me an Int
. There's no instance for Fractional Int
(read as, 'Int
isn't a Fractional
type') and I need it to be because you're passing an Int
into something that requires that instance."
的原因
我的代码,其中 n = 4:
f n = map (4/) [1..n]
main = do
n <- getLine
print(f (product(map read $ words n :: [Int])))
如果我在终端 map (4/) [1..n]
中使用,我会得到正确答案:[4.0,2.0,1.3333333333333333,1.0]
。
但在我的程序中它不起作用,错误消息是:No instance for (Fractional Int) arising from a use of
f'`
我的错误在哪里?
您的 n
是 Int
类型,而不是 Fractional
类型。这些是使用 /
运算符支持除法的那些。您可以将 /
替换为 div
以获得整数除法(截断为整数),或者您可以添加 fromIntegral
将 n
转换为正确的类型。
您的代码应该类似于
f n = map (4/) [1..fromIntegral n]
进一步澄清:您的函数 f 最终对提供给它的参数进行除法。这导致类型推理引擎确定那些参数应该是 Fractional
类型。然后你在你的 main
中使用那个函数,你明确地给它一个 Int
。
这就是错误显示 "You gave me an Int
. There's no instance for Fractional Int
(read as, 'Int
isn't a Fractional
type') and I need it to be because you're passing an Int
into something that requires that instance."