我在Haskell中编写一个简单的程序,让用户输入2的幂的指数
power a = 2^a
main = do
number <- readLn
let x = (read number :: Int)
power x
我发现我需要将String
转换为Int
,但我仍然会收到以下错误:No instance for (Num (IO t0)) arising from a use of 'power'
如何使其正常工作?< / p>
答案 0 :(得分:6)
当你写出类型时会有所帮助。
power :: (Num a, Integral b) => b -> a
power a = 2^a
main :: IO ()
main = do
number <- getLine
let x = read number :: Int
power x
但让我们看看这些东西真的会回归。 power
看起来正确,但main
正在尝试返回Num a
,而不是IO ()
。 main
并不意味着返回值 - 你应该对它们做些什么。也许你想print
结果? print :: Show a => a -> IO ()
main :: IO ()
main = do
number <- getLine
let x = read number :: Int
print $ power x
答案 1 :(得分:1)
让它以这种方式运行 - number
不是Int
:
power :: (Num a, Integral b) => b -> a
power a = 2^a
main :: IO ()
main = do
number <- getLine
let x = read number
print $ power x