[英]how can i append a value to a list inside a tuple in Haskell?
例如,如果我有一個元組列表,例如[("a1", ["a2", "a3"]), ("b1", ["b2", "b3"])]
並且我想添加a4
使用a1
& a4
作為輸入來更新列表,以便我們得到[("a1", ["a2", "a3", "a4"]), ("b1", ["b2", "b3"])]
作為輸出,我將如何處理這個問題? 我知道我們不能從字面上“更新”一個元組,我必須制作一個全新的列表
您可以使用遞歸創建此函數:
updateValueUsingKey :: Eq a => a -> b -> [(a, [b])] -> [(a, [b])]
updateValueUsingKey a b ((a',bs):abs)
| a == a' = (a',bs++[b]):abs -- update value if found
| otherwise = (a',bs) : updateValueUsingKey a b abs -- otherwise keep on recursing
updateValueUsingKey a b [] = [] -- end the recursion if no more elements
如果您不能改變 List(更新現有元素),則對其進行 fmap。
如果您無法改變 List(縮小或擴展),則綁定它。
import Data.Maybe (fromJust)
-- lookup will scan the List of Tuples for the Key
-- Use Maybe since You dont know the Key you are looking may Exist or not
updateValueUsingKey :: Eq a => a -> b -> [(a, [b])] -> Maybe [(a, [b])]
updateValueUsingKey key value associatedList =
((++[value]) <$> lookup key associatedList)
>>= (\v -> return $ fmap (\p -> if (fst p) == key then (key, v) else p) associatedList)
-- If you know exactly the key exists then use fromJust to extract the Value out of Maybe
updateValueUsingKey' :: Eq a => a -> b -> [(a, [b])] -> [(a, [b])]
updateValueUsingKey' key value associatedList = fromJust $ updateValueUsingKey key value associatedList
您擁有的稱為關聯列表:每個元組由一個名稱和一個與該名稱關聯的值組成。 如果您只想按“名稱”(元組的第一個元素) lookup
,那么內置的lookup
功能就足夠了。 由於您想要更新列表,因此使用Map
會更容易,它(假設所有名稱都是唯一的)可以輕松地從您的列表中初始化。
import qualified Data.Map as M
type MyMap = M.Map String [String]
append :: String -> String -> MyMap -> MyMap
append k v = M.insertWith (flip (++)) k [v]
調用insertWith
的函數參數時,將新值作為其第一個參數,將現有值作為第二個參數。 因此, (++)
僅此一項就預先考慮您的新元素到列表中。 由於您想追加新值,請使用flip (++)
來反轉參數的順序。
例如:
> data = M.fromList [("a1", ["a2", "a3"]), ("b1", ["b2", "b3"])]
> data
fromList [("a1",["a2","a3"]),("b1",["b2","b3"])]
> append "a1" "a4" data
fromList [("a1",["a2","a3","a4"]),("b1",["b2","b3"])]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.