我想实现这个总和。我遇到了关于类型签名的问题。
这就是它在 Haskell 中的样子。
crowdWrong :: (Fractional b, Integral b) => b -> b
crowdWrong m = crowdWrong' m m
crowdWrong' :: (Fractional b, Integral b) => b -> b -> b
crowdWrong' m 1 = ((0.49) ^ (m-1)) * (0.51) * (choose m 1) * (0.98)
crowdWrong' m i = ((0.49) ^ (m-i)) * ((0.51) ^ i) * (choose m i) * (0.98)
+ (crowdWrong' m (i - 1))
choose :: Integer -> Integer -> Integer
choose n 0 = 1
choose 0 k = 0
choose n k = (choose (n-1) (k-1)) * n `div` k
GHCi 的输出为:
untitled.hs:5:55:
Could not deduce (b ~ Integer)
from the context (Fractional b, Integral b)
bound by the type signature for
crowdWrong' :: (Fractional b, Integral b) => b -> b -> b
at untitled.hs:(5,1)-(7,42)
`b' is a rigid type variable bound by
the type signature for
crowdWrong' :: (Fractional b, Integral b) => b -> b -> b
at untitled.hs:5:1
In the first argument of `choose', namely `m'
In the second argument of `(*)', namely `(choose m 1)'
In the first argument of `(*)', namely
`((0.49) ^ (m - 1)) * (0.51) * (choose m 1)'
Failed, modules loaded: none.
我不知道如何解决这个问题,我想这会容易得多。
编辑:
所以现在我有这个:
crowdWrong :: Num b => Integer -> b
crowdWrong m = crowdWrong' m m
crowdWrong' :: Num b => Integer -> Integer -> b
crowdWrong' m 1 = ((0.49) ^ (m-1)) * (0.51) * (choose m 1) * (0.98)
crowdWrong' m i = ((0.49) ^ (m-i)) * ((0.51) ^ i) * (choose m i) * (0.98)
+ (crowdWrong' m (i - 1))
choose :: Integer -> Integer -> Integer
choose n 0 = 1
choose 0 k = 0
choose n k = (choose (n-1) (k-1)) * n `div` k
不过,GHCI 仍然在抱怨。
untitled.hs:5:48:
Could not deduce (b ~ Integer)
from the context (Num b)
bound by the type signature for
crowdWrong' :: Num b => Integer -> Integer -> b
at untitled.hs:(5,1)-(7,42)
`b' is a rigid type variable bound by
the type signature for
crowdWrong' :: Num b => Integer -> Integer -> b
at untitled.hs:5:1
In the return type of a call of `choose'
In the second argument of `(*)', namely `(choose m 1)'
In the first argument of `(*)', namely
`((0.49) ^ (m - 1)) * (0.51) * (choose m 1)'
Failed, modules loaded: none.