鍵值對 指定從鍵值對串列中檢索給定鍵值的函式。如果鍵未列出,則回傳默認值。函式的第一個引數應該是要搜索的鍵,第二個應該是默認值,第三個應該是串列!
我想歸還串列的其余部分,但我不知道如何在我的代碼中創建它。有人可以幫忙嗎?
value :: Eq a => a -> b -> [(a, b)] -> b
value a b ((c, d): xs)
| a == c = d
| otherwise = b -- : value xs ?
Examples:
value "aaa" "notFound" [] == "notFound"
value "1" "notFound" [("1", "haskell")] == "hasFell"
value 5 "" [(0, "c "), (5, "python"), (4, "rust")] == "python"
value 4 "" [(0, "c "), (5, "python"), (4, "rust")] == "rust"
value 4 "" [(0, "c "), (5, "python"), (4, "go")] == "go"
value 5 "scala" [(0, "c "), (5, "python")] == "python"
value 3 "scala" [(0, "c "), (1, "java"), (5, "python"), (4, "rust")] == "scala"
value 'b' False [('a', False), ('b', True)] == True
uj5u.com熱心網友回復:
有三種情況需要考慮:
- 串列為空
- 該串列不為空,并且密鑰與第一對匹配。
- 該串列不為空,并且密鑰與第一對不匹配。
您正確地確定了案例 2 的操作,但您沒有考慮案例 1。在案例 3 中,您需要執行相同型別的查找,但現在串列更短(因為您可以忽略第一對);您只需要使用適當的引數進行遞回。
value :: Eq a => a -> b -> [(a, b)] -> b
value key def [] = ? -- What do you return when the list is empty
value key def ((k, v):rest) | key == k = v
| otherwise = value ? ? ? -- What arguments do you pass now?
提示:空串列的情況很重要,不僅因為您想涵蓋所有可能性,還因為如果您需要回傳默認值,遞回呼叫最終將在空串列上呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/446000.html
