简体   繁体   中英

Haskell Error while using foldr to find sum.

I'm finding sum of fibonacci series numbers. And this is where I'm stuck at:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

main = do putStrLn "Enter a number:"
          num <- readLn
          foldr (+) 0 (take num fibs)

Error being:

No instance for (Num (IO t0))
  arising from the literal `0'
Possible fix: add an instance declaration for (Num (IO t0))
In the second argument of `foldr', namely `0'
In the expression: foldr (+) 0 (take num fibs)
In the expression:
  do { putStrLn "Enter a number:";
       num <- readLn;
       foldr (+) 0 (take num fibs) }

Where exactly am I going wrong?

You probably wanted to print the result:

main = do putStrLn "Enter a number:"
          num <- readLn
          print $ foldr (+) 0 (take num fibs)

The reason for the error message is that every statement in a do block must belong to the same monad. In the case of main , that's IO . However, the result of foldr here is a number, not an IO action.

The error message is confusing because GHC in all its wisdom concludes that IO actions must be numbers, which is of course nonsense.

When you are faced with a confusing type error, it's often useful to add some type annotations to some of the expressions involved, explaining to GHC what types you were expecting. That will often give you much better error messages back from GHC.

For example, if you add :: Integer at the end of the line with foldr , you'll get this message instead:

Couldn't match expected type `IO b0' with actual type `Integer'
In a stmt of a 'do' block: foldr (+) 0 (take num fibs) :: Integer
In the expression:
  do { putStrLn "Enter a number:";
       num <- readLn;
         foldr (+) 0 (take num fibs) :: Integer }
In an equation for `main':
    main
      = do { putStrLn "Enter a number:";
             num <- readLn;
               foldr (+) 0 (take num fibs) :: Integer }

Here it is much easier to see the problem. GHC was expecting a statement of type IO b0 , and you gave it an Integer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM