我想查看列表是否包含在另一个列表中并从列表列表中提取该列表,例如我想查看["bc","abc"]
中是否包含[["a","b","c","a","b","c","de"],["a","bc","abc","de"],["a","bc","abc","d","e"],....]
并且我想制作列出特定列表的列表,例如[["a","bc","abc","de"],["a","bc","abc","d","e"]]
。
对于[["aabbcc","aacc"]]
,我想仅匹配此["cc","aabbcc","aacc"]
或["c","c","aabbcc","aacc"]
但不匹配[["ccaabbcc","aacc"]]
。
有人能帮助我吗?
答案 0 :(得分:4)
根据我的理解,你想要一些关心列表中元素顺序的东西
如果你关心元素的顺序:
import Data.List (subsequences)
included :: Eq a => [a] -> [[a]] -> [[a]]
included ls nest = filter (\x -> any (ls==) $ subsequences x) nest
TEST:
*Main> included [1,2,3,4] [[1,3,4,5,2],[1,2,4,5],[1,2,3,4,5]]
[[1,2,3,4,5]]
如果您不关心元素的顺序:
import Data.List (subsequences, permutations, concat)
included :: Eq a => [a] -> [[a]] -> [[a]]
included ls nest = filter func nest
where
func x = any (ls==) $ concat $ map subsequences $ permutations x
TEST:
*Main> included [1,2,3,4] [[1,3,4,5,2],[1,2,4,5],[1,2,3,4,5]]
[[1,3,4,5,2],[1,2,3,4,5]]
答案 1 :(得分:3)
假设评论中我的问题的答案是否定的,
import Data.List
g :: (Eq a) => [a] -> [[a]] -> [[a]]
g a xs = [x | x <- xs,
or [and . map (uncurry (==)) $ zip a y | y <- init $ tails x]]
测试:
Prelude Data.List> g ["bc","abc"] [["a","bc","a","abc","de"],["a","bc","abc","de
"],["a","bc","abc","d","e"]]
[["a","bc","abc","de"],["a","bc","abc","d","e"]]
答案 2 :(得分:2)
假设评论中Will的问题答案为“否”:
import Data.List (isInfixOf)
foo :: Eq a => [a] -> [[a]] -> [[a]]
foo needle haystack = filter (needle `isInfixOf`) haystack
(未测试)。