简体   繁体   English

Haskell元组搜索列表

[英]Haskell List of Tuple Search

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 ? 知道怎么做吗?

Use Data.Map like this : 像这样使用Data.Map

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"): 让我们将54替换为78(在“df”上):

m2 = Map.insert "df" 78 m1

You can use insertWith' to combine the old and new values with a function. 您可以使用insertWith'将旧值和新值与函数组合。

Here we insert 4 on "username", and 4 is added to whatever value "username" points to. 这里我们在“用户名”上插入4,并将4添加到“用户名”指向的任何值。

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 . 这给出了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 . 键上有拼写错误,因此返回Nothing

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

If you use the Data.Map type you can use functions like 如果使用Data.Map类型,则可以使用类似的函数

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. 最后,您可以使用Data.Map.toList将事物返回到值列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM