我寫了一個函數,(應該)採取布爾的無限列表和計算時真亦假值在第一n個元素的比例:型鑄造在Haskell,分數和Int
prob n list = foldr (+) 0 (map boolToInt (take n list))/n
where boolToInt b
| b == True = 1
| otherwise = 0
不幸這不是工作:
No instance for (Fractional Int)
arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Int)
In the expression: foldr (+) 0 (map boolToInt (take n list))/n
In an equation for `prob':
prob n list
= foldr (+) 0 (map boolToInt (take n list))/n
where
boolToInt b
| b == True = 1
| otherwise = 0
Failed, modules loaded: none.
我試圖做一個轉換,但不工作之一:
prob n list = foldr (+) 0 (map boolToInt (take (fromIntegral (toInteger n)) list))/n
where boolToInt b
| b == True = 1
| otherwise = 0
它的編制,但只要我嘗試調用的函數,我得到一個錯誤:
*Main> prob 50 toCoin1
<interactive>:1:6:
Ambiguous type variable `a0' in the constraints:
(Num a0) arising from the literal `50' at <interactive>:1:6-7
(Integral a0) arising from a use of `prob' at <interactive>:1:1-4
(Fractional a0) arising from a use of `prob' at <interactive>:1:1-4
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `prob', namely `50'
In the expression: prob 50 toCoin1
In an equation for `it': it = prob 50 toCoin1
有什麼建議?
這不適合我,應'fromRational'是'fromIntegral'? – huon 2012-03-10 02:57:19
@dbaupp:呃,是的,它應該。猜猜我不應該在網絡瀏覽器中編碼。 – 2012-03-10 03:03:06
@dbaupp:如果您爲'prob'編寫頂級類型聲明,例如'prob :: Int - > [Bool] - > Float',那麼你會得到一個更好的錯誤信息。 – 2012-03-10 03:05:06