0

這裏是我的代碼:混淆類型ghci中

n = [(a,b) | a <- [1..5],b <- [1..5]] 
calcBmis xs = [bmi | (w, h) <- xs,let bmi = w/h^2] 

當試圖申請calcBmisn,我得到以下錯誤:

*Charana> calcBmis n 

<interactive>:220:1: 
    No instance for (Fractional Integer) 
    arising from a use of ‘calcBmis’ 
    In the expression: calcBmis n 
    In an equation for ‘it’: it = calcBmis n 

在ghci中進一步的調查:

*Charana> :t calcBmis 
calcBmis :: Fractional t => [(t, t)] -> [t] 
*Charana> :t n 
n :: [(Integer, Integer)] 

我在假設我製作的清單是(Integer,Integer) ,但是不能在calcBmis中處理,僅在Fractional。任何想法如何解決這個問題?

回答

2

可以使用div代替(/)

calcBmis xs = [ bmi | (w,h) <- xs, let bmi = (w `div` h)^2 ] 

Prelude> :t calcBmis 
calcBmis :: Integral t => [(t, t)] -> [t] 

Prelude> calcBmis n 
[1,0,0,0,0,4,1,0,0,0,9,1,1,0,0,16,4,1,1,0,25,4,1,1,1] 

,你可以看到這個版本可以處理所有Integral值 - 但當然會截斷(因爲div)。

,或者你可以映射一切與fromIntegral:因爲它們的實例在這兩種情況下

Prelude> calcBmis n 
[1.0,0.25,0.1111111111111111 
,6.25e-2 
,4.000000000000001e-2 
,4.0 
,1.0 
,0.4444444444444444 
, ... ] 

它將與所有輸入,只要工作:

calcBmis xs = [ bmi | (w,h) <- xs, let bmi = (fromIntegral w/fromIntegral h)^2 ] 

Prelude> :t calcBmis 
calcBmis:: (Fractional t, Integral t1, Integral t2) => [(t1, t2)] -> [t] 

,然後將產生的分數值Integral - 第二個版本甚至會接受不同積分對;)

+0

美麗,謝謝 – Charana