简体   繁体   English

使用文件夹查找总和时出现Haskell错误。

[英]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: 您可能想print结果:

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. 该错误消息的原因是, do块中的每个语句必须属于同一monad。 In the case of main , that's IO . main的情况下,这是IO However, the result of foldr here is a number, not an IO action. 但是,这里的foldr结果是一个数字,而不是IO操作。

The error message is confusing because GHC in all its wisdom concludes that IO actions must be numbers, which is of course nonsense. 该错误消息令人困惑,因为GHC的所有智慧得出的结论是, IO操作必须是数字,这当然是胡说八道。

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. 当您遇到令人困惑的类型错误时,在某些涉及的表达式中添加一些类型注释通常很有用,向GHC解释您期望的类型。 That will often give you much better error messages back from GHC. 这通常会使您从GHC返回更好的错误消息。

For example, if you add :: Integer at the end of the line with foldr , you'll get this message instead: 例如,如果在foldr行的末尾添加:: Integer ,则会得到以下消息:

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 . GHC期待的是IO b0类型的语句,而您给了它一个Integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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