我知道标准的方式是
(Eq z) => matchLists :: [x] -> [x] -> Bool
matchLists xs ys = xs == ys
Run Code Online (Sandbox Code Playgroud)
但我有一个特殊的元素匹配函数,它从外部传递,我无法控制它.
所以我正在寻找的是
matchLists :: (x -> x -> Bool) -> [x] -> [x] -> Bool
Run Code Online (Sandbox Code Playgroud)
(Hoogle说没有)
你最终会得到一个带有这样的签名的自定义函数,或者你会做什么?
编辑:
zip函数不能满足我的需要,因为结果列表具有2个输入列表中的最小长度
编辑:
你觉得这怎么样?
--matchListsWith :: (a -> a -> Bool) -> [a] -> [a] -> Bool
matchListsWith :: (a -> b -> Bool) -> [a] -> [b] -> Bool
matchListsWith _ [] [] = True
matchListsWith _ (_:_) [] = False
matchListsWith _ [] (_:_) = False
matchListsWith matcher (x:xs) (y:ys) = matcher x y && matchListsWith matcher xs ys
Run Code Online (Sandbox Code Playgroud)
使用Data.Align我们可以同时处理压缩和长度问题
matchWith :: (a -> b -> Bool) -> [a] -> [b] -> Bool
matchWith f as bs = and $ alignWith combiner as bs where
combiner = these (const False) (const False) f
Run Code Online (Sandbox Code Playgroud)
这将显示与显式递归函数相同的代码,但使用标记Data.These来标记各种列表对齐.如果你概括了它,它也可以推广到许多其他结构,如树或序列and.
matchWith :: (Foldable f, Align f) => (a -> b -> Bool) -> f a -> f b -> Bool
matchWith f as bs = Foldable.and $ alignWith combiner as bs where
combiner = these (const False) (const False) f
data Tree a = Tip | Branch a (Tree a) (Tree a) deriving ( Functor, Foldable )
instance Align Tree where
nil = Tip
align Tip Tip = Tip
align (Branch a la ra) Tip = Branch (This a) (fmap This la) (fmap This ra)
align Tip (Branch b lb rb) = Branch (That b) (fmap That lb) (fmap That rb)
align (Branch a la ra) (Branch b lb rb) =
Branch (These a b) (align la lb) (align ra rb)
Run Code Online (Sandbox Code Playgroud)
所以我们有
?> matchWith (==) Tip Tip
True
?> matchWith (==) (Branch 3 Tip Tip) (Branch 3 Tip Tip)
True
?> matchWith (==) (Branch 3 Tip Tip) (Branch 3 Tip (Branch 3 Tip Tip))
False
Run Code Online (Sandbox Code Playgroud)
(不妨...)
instance Eq a => Eq (Tree a) where (==) = matchWith (==)
Run Code Online (Sandbox Code Playgroud)