这些是我的haskell列表
lst1 = ["a,","b","c"]
lst2 = [("a","123"),("b","345")]
我想从“lst1”获取一个元素并与“lst2”进行比较,如果该值存在,则要替换为元组中的第二个值,替换第二个值。
所以就像这样 lst1有“a”和“b”所以输出应该是[“123”,“345”,“c”] 那我怎样才能在哈斯克尔做到这一点? 请帮助我 我可以用其他任何方式吗? thankxx!
答案 0 :(得分:2)
我就是这样做的。
import qualified Data.Map as M
import Data.Maybe
lst1 = ["a","b","c"]
lst2 = [("a","123"),("b","345")]
-- For each value of lst1, you want to replace it by something, so you'll be using map '
res = map comb lst1
-- For performance, we convert the 2nd list to a map
m = M.fromList lst2
-- For a value of lst1, you want to find it in the map,
-- and return the result if found,
-- or keep the original if not found
comb v = fromMaybe v (M.lookup v m)
前奏> :R t
[1/1]编译Main(t.hs,解释)
好的,模块已加载:Main。
*主> RES
加载包array-0.3.0.1 ...链接...完成。
加载包容器-0.3.0.0 ...链接...完成。
[ “123”, “345”, “C”]
*主>
答案 1 :(得分:2)
map (\x -> maybe x snd $ find ((x ==).fst) lst2) lst1
对于较长的列表,您应该考虑使用Map而不是lst2
[编辑]
import Data.Maybe
subst lst1 lst2 = map (\x -> fromMaybe x $ lookup x lst2) lst1
(感谢Chuck)
只是为了一些无意义的乐趣:
import Data.Maybe
main = print $ subst [("a","123"),("b","345")] ["a","b","c"]
subst = map.app fromMaybe lookup
where app f g x y = f y $ g y x
易于编写且非常难以理解(至少对我而言)Haskell代码的完美示例,因此我肯定会使用其他定义之一。