这是我到目前为止所做的,我很确定函数本身是正确的,但我对main = do块中的操作感到困惑。 我得到的错误是该函数想要一个整数但我给它一个字符串而不是。我假设它与getLine部分有关,而且我没有检查输入的数字是否为int。
factors :: Int -> [Int]
factors n = [x | x <- [1..n], mod n x == 0]
primeFactors :: Int -> [Int]
primeFactors n = [x | x <- [1..n], mod n x == 0, isPrime x]
isPrime x = (length (factors x)) == 2
main = do
putStrLn "Enter a number."
number <- getLine
let x = factors number
putStrLn x
运行此代码时出现的错误:
primeFactor.hs:9:19:错误:
• Couldn't match type ‘[Char]’ with ‘Int’ Expected type: Int Actual type: String • In the first argument of ‘factors’, namely ‘number’ In the expression: factors number In an equation for ‘x’: x = factors number
primeFactor.hs:10:12:错误:
• Couldn't match type ‘Int’ with ‘Char’ Expected type: String Actual type: [Int] • In the first argument of ‘putStrLn’, namely ‘x’ In a stmt of a 'do' block: putStrLn x In the expression: do { putStrLn "Enter a number."; number <- getLine; let x = factors number; putStrLn x }
答案 0 :(得分:3)
let x = factors $ (read number :: Int)
print x
OR
number <- readLn
(感谢@Daniel)
这应该做的工作。