你本质上想要map字符串列表的函数(您称之为“模板”),即该函数
- 需要一个字符串
xs
,
- returns
-
(xs, Just n)
如果一个整数n
关联到xs
在您的“要验证的列表”中,
-
(xs, Nothing)
否则。
这是一种可能的方法:
import Data.List ( lookup )
import Control.Monad ( join )
consolidate :: [String] -> [(String, Maybe Int)] -> [(String, Maybe Int)]
consolidate temp l = map (\xs -> (xs, join $ lookup xs l)) temp
但是,如果您构建一个,您将获得更快的查找速度Map保存关联列表的键值对(“要验证的列表”):
import qualified Data.Map as M
import Data.Maybe (maybe)
consolidate :: [String] -> [(String, Maybe Int)] -> [(String, Maybe Int)]
consolidate temp l = map (\cs -> (cs, M.lookup cs $ fromList' l)) temp
fromList' :: Ord a => [(a, Maybe b)] -> M.Map a b
fromList' xs = foldr insertJust M.empty xs
insertJust :: Ord a => (a, Maybe b) -> M.Map a b -> M.Map a b
insertJust (xs, maybeVal) mp = maybe mp (\n -> M.insert xs n mp) maybeVal
In GHCi:
λ> let myTemplate = ["hello", "world", "this", "is", "a", "test"]
λ> let myList = [("hello", Just 1), ("world", Just 2), ("test", Just 3)]
λ> consolidate myTemplate myList
[("hello",Just 1),("world",Just 2),("this",Nothing),("is",Nothing),("a",Nothing),("test",Just 3)]