Haskell元组搜索列表 [英] Haskell List of Tuple Search

查看:98
本文介绍了Haskell元组搜索列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我需要根据用户名搜索值。我使用查找,但我需要更改整数的值并写回文件。我的逻辑是删除元组并插入另一个新的元组值,而不是改变它。



任何想法如何做到这一点? 使用 Data.Map 像这样:

 将限定的Data.Map导入为Map 

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

让我们用78代替54(在df上):

  m2 = Map.insertdf78 m1 

您可以使用insertWith'to



在这里,我们在用户名中插入4,并将4添加到用户名指向的任何值。

  m3 = Map.insertWith(+)username4 m1 

如果您确定某个键在地图中,则可以使用(!)运算符访问其值:

 导入Data.Map((!))
m3! username

给出 127 。但要小心,如果钥匙不在地图中,它可能会引发异常!



为了安全查找:

  Map.lookup :: Map ka  - > k  - >可能是
Map.lookupusrnamem3

键上有一个错字,所以这返回 Nothing


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 :

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.

这篇关于Haskell元组搜索列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆