haskell - 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
任何想法我哪里出错了?任何帮助,将不胜感激
解决方案
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))
在这里,我们同时迭代两个列表,并比较元素。因此,如果两个列表的元素匹配,我们就会创建一个Bool
s列表。True
然后我们使用takeWhile
只要 item 是 就取元素True
,并且我们使用length
来确定该列表中的元素数量。由于 Haskell 的惰性,如果其中一个元素与另一个列表中的相应元素不同,我们将永远不会评估整个列表。
推荐阅读
- algorithm - 为什么该算法适用于二次探测?
- c# - 为什么随机数没有正确分散?
- web-scraping - 挣扎于 Scrapy 分页
- java - 如何在app中提取网站的html代码
- javascript - 函数将一行作为字符串附加到表中
- mongodb - 在使用 GORM mongoDB 插件的 Grails 应用程序中配置 MongoDatastore 类的 bean 覆盖的最佳方法是什么?
- apache-spark - PySpark:aggregate() 正好需要 4 个参数(给定 3 个)
- google-sheets - 在文本字符串中的任何值出现在 Google 表格中之前和之后添加文本字符串
- python - 如何以编程方式运行主/从 Locust 跑步者,以便奴隶在最后停止
- javascript - 将变量放在 React 组件中的什么位置?