1

I'm writing a simple program in Haskell that lets user input exponent of the power of 2

power a = 2^a
main = do
   number <- readLn
   let x = (read number :: Int)
   power x


I figured out that I need to convert String to Int but i still get following error: No instance for (Num (IO t0)) arising from a use of 'power'
How do I make it work?

1
  • 6
    reading after readLn is a bad idea. readLn = readIO =<< getLine so you'll read a line, parse that into a String (requiring proper quoting and escaping), and then parse that again into a number. Just use readLn Commented Dec 3, 2017 at 22:18

2 Answers 2

6

It helps when you write out the types.

power :: (Num a, Integral b) => b -> a
power a = 2^a

main :: IO ()
main = do
  number <- getLine
  let x = read number :: Int
  power x

But let's look what these things really return. power looks right, but main is trying to return a Num a, not an IO (). main is not meant to return values -- you should do something with them. Maybe you want to print the result? print :: Show a => a -> IO ()

main :: IO ()
main = do
  number <- getLine
  let x = read number :: Int
  print $ power x
Sign up to request clarification or add additional context in comments.

5 Comments

This code compiles fine but when I'm trying to run .exe file I get this message: user error (Prelude.readIO: no parse)
it's working after changing readLn to getLine as @HTNW suggested
@KubaKrzyżyński whoops, yes :)
@KubaKrzyżyński I suggest you use readMaybe from Text.Read instead of read because read is not total.
Or use number <- readLn as in the original. But there is no need to read the number -- readLn already does that for you. Just print $ power number
1

Got it running that way - number is not an 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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.