[英]How can I fix my haskell code to work for my example?
代碼運行良好,但在我的示例中嘗試時得到了錯誤的結果。 問題是我示例中的這一部分:[-9..10]。 此列 avarage 為 0.5,但我測試時得到 0。 haskell 在這個例子中使用了空列表匹配模式,但我不知道為什么。 我怎樣才能解決這個問題?
listAvg :: [Double] -> Double
listAvg [] = 0
listAvg x = (sum x)/fromIntegral(length x)
coldestAvg :: [[Double]] -> Double
coldestAvg [] = 0
coldestAvg (x:xs) = min (listAvg x) (coldestAvg xs)
Example :
coldestAvg [[12,13],[-9..10]] == 0.5
haskell 在這個例子中使用了空列表匹配模式,但我不知道為什么。 我怎樣才能解決這個問題?
您每次都使用列表的尾部xs
進行遞歸調用。 因此,最終您將使用空列表調用coldestAvg
,並且由於在這種情況下0
是所有平均值中最小的,因此它將返回0
。
您不應該定義這樣的基本情況:空列表沒有最小值。 對於只有一個元素的列表,您返回平均值,因此:
coldestAvg :: [[Double]] -> Double
coldestAvg [x] = listAvg x
coldestAvg (x:xs) = min (listAvg x) (coldestAvg xs)
您需要將coldestAvg [] = 0
更改為coldestAvg [] = 1/0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.