實作
populationBelow :: Int -> [(String, Int)] -> [String]函式,該函式回傳給定表中人口(百萬人)小于引數中給定數字的國家名稱。例如:
populationBelow 10 [ ("Hungary", 9.773),
("Japan", 126.8),
("Iceland", 0.3604),
("United States", 327.2),
("Mongolia", 3.076)
] == ["Hungary", "Iceland", "Mongolia"]
populationBelow 0 [ ("Hungary", 9.773),
("Japan", 126.8),
("Iceland", 0.3604),
("United States", 327.2),
("Mongolia", 3.076)] == []
到目前為止,我已經嘗試過:
populationBelow x ((y, z):ys) | z < x = [y] populationBelow x (ys)
| otherwise = (y) : populationBelow x (ys)
這不適用于小數,如果表格包含多個符合條件的元素,我會收到Non-exhaustive patterns錯誤訊息。
uj5u.com熱心網友回復:
populationBelow :: RealFrac a => a -> [(String, a)] -> [String]
populationBelow _ [] = []
populationBelow x ((y, z):ys)
| z < x = y : populationBelow x ys
| otherwise = populationBelow x ys
目前的代碼有幾個問題:
- 空串列的基本情況(因此出現非窮盡模式錯誤),無論是因為遞回而耗盡還是首先是空的,都缺失了。
y無論條件的結果如何,您都將添加到結果中。在第一種情況下通過連接,第二種情況通過將其添加到遞回呼叫結果的頭部。y僅當其人口低于給定閾值時才應添加。- 您的函式提供的簽名表明它僅使用整數,但輸入示例具有十進制數。我已更改簽名以接受十進制數字。
uj5u.com熱心網友回復:
你絕對是在正確的軌道上。為了能夠處理小數,您應該使您的型別簽名更通用。此外,相當簡單的過濾任務可以說是最優雅地表達為串列推導式:
populationBelow :: Ord b => b -> [(a, b)] -> [a]
populationBelow k xs = [x | (x, n) <- xs, n < k]
的確:
> populationBelow 10 [("Hungary", 9.773), ("Japan", 126.8), ("Iceland", 0.3604), ("United States", 327.2), ("Mongolia", 3.076)]
["Hungary","Iceland","Mongolia"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/334073.html
