[英]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.