我有这个功能:
applyRel :: (Eq k) => k -> (BinaryRelation k v) -> [v]
applyRel key list = [ v | (k,v)<-list, key==k]
并且它需要一个字符串,k并返回具有给定k的所有v:
applyRel&#34; bar&#34; bar_stuff
会输出
[&#34; mitzva&#34;,&#34;凳子&#34;,&#34;招标&#34;,&#34;饲养员&#34;]
它可以工作,但如果它包含字符串列表和另一个列表,该怎么办呢? 我可以执行类似列表递归的操作,遍历列表并且每个项目遍历第二个列表。有点像C中的双循环。
这就是我的目标:
applyToList :: [k] -> (BinaryRelation k v) -> [v]
applyToList [] list = []
applyToList keys list =
do key <- keys
applyRel key list
答案 0 :(得分:1)
如果您将Eq k
约束添加到applyToList
:
applyToList :: Eq k => [k] -> BinaryRelation k v -> [v]
applyToList keys list = do
key <- keys
applyRel key list
您也可以在[]
上省略模式匹配。工作示例:
> let bar_stuff = [("bar", "mitzva"), ("bar", "stool"), ("bar", "tender"), ("bar", "keeper"), ("salad", "bar"), ("foo", "bar")]
> applyToList ["salad", "bar"] bar_stuff
["bar","mitzva","stool","tender","keeper"]
或者你可以使用concatMap
,Monad
实例中使用applyToList :: Eq k => [k] -> BinaryRelation k v -> [v]
applyToList keys list = concatMap (flip applyRel list) keys
来表示列表:
{{1}}