Haskell List of Tuple Search

纵饮孤独 提交于 2019-12-05 23:38:06

问题


I have a list of tuples like this:

[("username", 123), ("df", 54), ("as",2 34)]

I need to search the value based on username. I have using lookup but i need to change the value of the integer and write back to file. My logic of this is to delete the tuple and insert another new tuple value rather than change it.

Any idea how to do this ?


回答1:


Use Data.Map like this :

import qualified Data.Map as Map

m1 :: Map String Int
m1 = Map.fromList [("username", 123), ("df", 54), ("as",234)]

Let's replace 54 by 78 (on "df"):

m2 = Map.insert "df" 78 m1

You can use insertWith' to combine the old and new values with a function.

Here we insert 4 on "username", and 4 is added to whatever value "username" points to.

m3 = Map.insertWith (+) "username" 4 m1

If you're sure that a key is in the map, you can access its value using the (!) operator :

import Data.Map ((!))
m3 ! "username"

Which gives 127. But beware, it could raise an exception if the key isn't in the map!

For safe lookup :

Map.lookup :: Map k a -> k -> Maybe a
Map.lookup "usrname" m3

There is a typo on the key, so this returns Nothing.




回答2:


repList old new xs = map (\v@(x,y) -> if x == old then (new,y) else v) xs



回答3:


If you use the Data.Map type you can use functions like

updatedMap = Data.Map.updateWithKey (\_ _ -> Just 234) "username" myMap

With the way you give your list, you have to construct the map by something like

myMap = Data.Map.fromList (map (\ (a,b) -> (b,a)) datalist)

Finally, you can get things back to a list of values by using Data.Map.toList.



来源:https://stackoverflow.com/questions/3082571/haskell-list-of-tuple-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!