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

Kar*_*rek 1 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)))
Run Code Online (Sandbox Code Playgroud)

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

opq*_*nut 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)))'
Run Code Online (Sandbox Code Playgroud)

你看,问题是你传递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)
Run Code Online (Sandbox Code Playgroud)

  • 从技术上讲,对于充分病态的`x`,你可能会得到溢出预转换,这可能会导致不同的结果,因为Float不会以相同的方式溢出...但是,是的,足够接近所有合理的值:) (2认同)