无法将预期类型整数与实际类型float匹配

时间:2011-12-20 21:51:30

标签: haskell

countSequences :: Int -> Int -> Integer

countSequences 0 m = 0
countSequences m 0 = 0
countSequences (n) (m) =  if (n <= (m+1)) then (truncate((cee (m+1) (n) (0))) + truncate((countSequences (fromIntegral (n-1)) (fromIntegral (m))))) 
else truncate(countSequences (fromIntegral (n-1)) (fromIntegral (m)))

factorial :: Float -> Float
factorial 0 = 1
factorial 1 = 1
factorial x = x * factorial(x-1)

cee :: Float -> Float -> Float -> Float

cee x y z = if (x==y) then ((1) / (factorial ((x+z)-(y)))) else ((x) * (cee (x-1) (y) (z+1)))

我真的不明白为什么这个错误不断出现.. truncate应该将类型从Float转换为Integer所以..

2 个答案:

答案 0 :(得分:5)

错误是:

Couldn't match expected type `Float' with actual type `Int'
In the first argument of `(+)', namely `m'
In the first argument of `cee', namely `(m + 1)'
In the first argument of `truncate', namely
  `((cee (m + 1) (n) (0)))'

你知道,问题是你将Int传递给了函数cee

在这里,我为你清理了代码:

countSequences :: Int -> Int -> Integer

countSequences 0 m = 0
countSequences m 0 = 0
countSequences n m = 
  if n <= m+1
  then truncate (cee (fromIntegral (m+1)) (fromIntegral n) 0) +
       countSequences (n-1) m
  else countSequences (n-1) m

factorial :: Float -> Float
factorial 0 = 1
factorial 1 = 1
factorial x = x * factorial (x-1)

cee :: Float -> Float -> Float -> Float

cee x y z =
  if (x==y)
  then 1 / factorial (x+z-y)
  else x * cee (x-1) y (z+1)

答案 1 :(得分:2)

m属于Int类型(根据countSequences的类型签名:因此,m + 1也是如此。但是,您的函数cee需要{ {1}},所以类型检查员会抱怨。

此外,您还需要几个修复程序来进行此类型检查。这是一个通过检查程序的版本:

Float