首页 > 解决方案 > Haskell:比较序列并计算常见前缀的长度

问题描述

我是haskell的新手,我正在编写一个比较两个序列并报告它们共同前缀长度的函数。这是我到目前为止所拥有的,但它并不适用于所有情况。

commonLen :: Eq a => [a] -> [a] -> Int
commonLen (x:xs) [] = 0
commonLen (x:xs) (y:ys) | x==y = 1+(commonLen xs ys)
                        | otherwise = commonLen xs ys

任何想法我哪里出错了?任何帮助,将不胜感激

标签: haskellcomparesequence

解决方案


x如果与 不同,则不应递归y。在这种情况下,我们返回0

commonLen :: Eq a => [a] -> [a] -> Int
commonLen [] _ = 0
commonLen _ [] = 0
commonLen (x:xs) (y:ys) | x == y = 1 + commonLen xs ys
                        | otherwise = 0  -- ← return 0

您还可以避免显式递归,并使用:

commonLen :: Eq a => [a] -> [a] -> Int
commonLen xs ys = length (takeWhile id (zipWith (==) xs ys))

在这里,我们同时迭代两个列表,并比较元素。因此,如果两个列表的元素匹配,我们就会创建一个Bools列表。True然后我们使用takeWhile只要 item 是 就取元素True,并且我们使用length来确定该列表中的元素数量。由于 Haskell 的惰性,如果其中一个元素与另一个列表中的相应元素不同,我们将永远不会评估整个列表。


推荐阅读