【问题标题】:Haskell: Couldn't match expected type 'IO t0' with actual type 'Integer'Haskell:无法将预期类型“IO t0”与实际类型“Integer”匹配
【发布时间】:2016-04-14 04:31:16
【问题描述】:

当我尝试编译我的代码时:

[1 of 1] Compiling Main             ( survey2.hs, survey2.o )

survey2.hs:20:1:
    Couldn't match expected type ‘IO t0’ with actual type ‘Integer’
    In the expression: main
    When checking the type of the IO action ‘main’

我尝试过将输入到 main 的 '9' 指定为一堆不同的类型,包括 IO、IO t、IO t0、int 等。我了解基于我拥有的函数定义在其他地方,如果一个 Integer 没有输入到函数中,那么其他函数都不会正常工作。我不确定如何将正确的类型放入 main 中。

factorial:: Integer -> Integer
factorial n
  | n <= 1    = 1 
  | otherwise =  n * factorial(n-1)

binomial :: (Integer, Integer) -> Integer
binomial (n, k)
  | k > n     = 0 
  | k < 0     = 0 
  | otherwise = factorial(n) / (factorial(n-k) * factorial(k))

bell :: Integer -> Integer
bell n
  | n <= 1    = 1 
  | otherwise = sum [ binomial(n-1, k-1)  * bell (k-1) | k<-[0..n-1] ] 

bellSum :: Integer -> Integer  
bellSum n = sum [ bell(k) | k<-[0..n] ]

main = bell(9 :: Integer )

【问题讨论】:

    标签: haskell functional-programming type-mismatch


    【解决方案1】:

    如果main在主模块中(通常称为Main),则它的类型必须为IO a(通常为IO ())。

    由于bell 9 的类型为Integer,因此类型不匹配。您需要打印Integerprint :: Show a =&gt; a -&gt; IO () Integer

    main = print (bell 9)
    

    注意(/)不适用于Integer,你需要使用div来代替:

    | otherwise = factorial(n) `div` (factorial(n-k) * factorial(k))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 2017-09-16
      • 2012-08-29
      • 2020-02-29
      相关资源
      最近更新 更多