gpt4 book ai didi

haskell - Haskell 中是否有一种标准方法可以使用自定义匹配函数来匹配 2 个列表?

转载 作者:行者123 更新时间:2023-12-02 10:29:28 24 4
gpt4 key购买 nike

我知道标准方法是

(Eq z) => matchLists :: [x] -> [x] -> Bool
matchLists xs ys = xs == ys

但是我有一个特殊的元素匹配函数,它是从外部传递的,我无法控制它。

所以我正在寻找的是

matchLists :: (x -> x -> Bool) -> [x] -> [x] -> Bool

(胡格尔说 no )

您最终会得到一个带有这样的签名的自定义函数还是您会做什么?

编辑:

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

最佳答案

使用Data.Align我们可以同时处理 zipper 和长度问题

matchWith :: (a -> b -> Bool) -> [a] -> [b] -> Bool
matchWith f as bs = and $ alignWith combiner as bs where
combiner = these (const False) (const False) f

这会展开与显式递归函数相同的代码,但使用 Data.These 中的标签来标记各种列表对齐方式。如果您概括 ,它还可以推广到许多其他结构,例如树或序列。

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)

这样我们就有了

λ> 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

(也许...)

instance Eq a => Eq (Tree a) where (==) = matchWith (==)

关于haskell - Haskell 中是否有一种标准方法可以使用自定义匹配函数来匹配 2 个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com