【发布时间】:2018-06-20 03:42:45
【问题描述】:
这是我遇到的一个家庭作业问题:
输入一个大于等于0的整数。乘以5,乘以6,乘以4,加9,乘5。然后,去掉最后两位数,减去1 . 输出答案。
这是我的代码:
1 main = do
2 putStrLn "enter a non-negative integer: "
3 input <- getLine
4 let i = (read input :: Int)
5 print ((((i * 5) + 6) * 4 + 9) * 5)/100-1
在这里,我试图通过将其除以 100 来截断最后两位数字,因为这适用于其他语言。 但是,它给了我这个错误,我不确定这意味着什么:
$ runhaskell Computations.hs
Computations.hs:5:5: error:
• No instance for (Fractional (IO ())) arising from a use of ‘/’
• In the first argument of ‘(-)’, namely
‘print ((((x * 5) + 6) * 4 + 9) * 5) / 100’
In a stmt of a 'do' block:
print ((((x * 5) + 6) * 4 + 9) * 5) / 100 - 1
In the expression:
do { putStrLn "enter a non-negative integer: ";
input1 <- getLine;
let x = (read input1 :: Int);
print ((((x * 5) + 6) * 4 + 9) * 5) / 100 - 1 }
Computations.hs:5:5: error:
• No instance for (Num (IO ())) arising from a use of ‘-’
• In a stmt of a 'do' block:
print ((((x * 5) + 6) * 4 + 9) * 5) / 100 - 1
In the expression:
do { putStrLn "enter a non-negative integer: ";
input1 <- getLine;
let x = (read input1 :: Int);
print ((((x * 5) + 6) * 4 + 9) * 5) / 100 - 1 }
In an equation for ‘main’:
main
= do { putStrLn "enter a non-negative integer: ";
input1 <- getLine;
let x = ...;
.... }
那么,谁能解释一下这个错误是什么意思?
还有比除数分割更好的解决方案吗?
如何删除任意位置的数字?比如去掉一个整数的第一个、第二个和第六个数字?
ps:如果输入正确,输入和输出应该匹配。
更新:我已将“/”更改为“div”,它给了我这个:
Computations.hs:5:12: error:
• Couldn't match expected type ‘(Integer -> Integer -> Integer)
-> Integer -> Integer’
with actual type ‘Int’
• The function ‘(((i * 5) + 6) * 4 + 9) * 5’
is applied to two arguments,
but its type ‘Int’ has none
In the first argument of ‘(-)’, namely
‘((((i * 5) + 6) * 4 + 9) * 5) div 100’
In the first argument of ‘print’, namely
‘(((((i * 5) + 6) * 4 + 9) * 5) div 100 - 1)’
这部分很奇怪:“函数'(((i * 5) + 6) * 4 + 9) * 5'应用于两个参数”,为什么haskell将其解释为函数?
【问题讨论】:
-
使用
div,而不是/。 -
整数除法是
div,而不是/。 -
@chepner,如果你省略了所述的前置条件,正确的除法运算将是
quot,而不是div。 -
如果你想像运算符一样使用
div,你必须把它放在反引号中。 -
仅供参考,您可以使用以下(imo 更容易理解)代码:
transform = (subtract 1) . (`quot` 100) . (*5) . (+9) . (*4) . (+6) . (*5),尽管回答“有没有比除数分割更好的解决方案?”在我的answer to your other question 中已经给出,所以这里可能不需要重复。
标签: haskell