【问题标题】:If a list element matches 1st tuple element replace it with 2nd tuple element如果列表元素与第一个元组元素匹配,则将其替换为第二个元组元素
【发布时间】:2016-10-31 07:11:02
【问题描述】:

我有 2 个列表:
- list1 作为元组形式的字典:
[("aaa", "bb"), ("d", "efg"), ("if found this", "replace with this")]
- list2 作为要翻译的元素列表:["aaa", "efg", "zzz"]

如果list2 元素匹配list1 元组第二个元素,我需要返回一个列表,其中list2 中的元素被替换为list1 元素中的元组第二个元素。在此示例中,结果列表如下所示 ["bb", "efg", "zzz"]

如何做到这一点? 我最近才开始学习 Haskell,所以语法是我的主要问题。我认为函数定义应该是这样的
replace :: Eq a => [(a,a)] -> [a] -> [a]
并且该函数应该执行类似尝试在元组中找到list2值的操作,如果找到保持元组中的值并递归调用函数replace,如果未找到值,则保持来自list2的值并递归调用函数replace

【问题讨论】:

    标签: haskell


    【解决方案1】:

    无需重新发明轮子。

    import qualified Data.Map as M
    
    list1 = [("aaa", "bb"), ("d", "efg"), ("if found this", "replace with this")]
    list2 = ["aaa", "efg", "zzz"]
    
    replace d = map (\k -> M.findWithDefault k k d)
    
    main = print $ replace (M.fromList list1) list2
    

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      相关资源
      最近更新 更多