Haskell转换类型错误

时间:2017-12-03 22:06:22

标签: haskell type-conversion

我在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>

2 个答案:

答案 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