haskell - 我正在尝试在 haskell 中重新定义产品定义。我收到一条错误消息,提示“功能中的非详尽模式”
问题描述
product' :: [Integer] -> Integer
product' (x:xs)
| (x:xs) == [] = 1
| otherwise = x * (product' (xs))
第一个不起作用并给出错误。下面的一个使用模式匹配技术并且工作正常。
productP :: [Integer] -> Integer
productP [] = 1
productP (x:xs) = x * (productP (xs))
解决方案
该(x:xs) == []
部分是无意义的:与(x:xs)
您构造一个包含至少一个元素的列表:x
作为第一个元素,并xs
作为剩余元素的(可能为空的)列表。因此,这将始终导致False
.
模式的要点(x:xs)
是它匹配非空列表。列表定义为:
data [a] = [] | (a:[a]) -- pseudo-code
因此,列表有两个数据构造函数:
- 空列表
[]
;和 (x:xs)
有一个 headx
和一个 tail的“缺点”xs
。x
是列表的一个元素,并且xs
是剩余元素的列表。
您可以检查xs
整个列表是否等于空列表,然后使用head
and tail
:
product' :: [Integer] -> Integer
product' xs
| xs == [] = 1
| otherwise = head x * product' (tail xs)
但是上面不是很优雅,因为head
和tail
是非全部函数(它们对于空列表会出错),因此“更难”确定这个函数总是会产生答案。
推荐阅读
- python - Pandas:根据其他多级列按组对最内列进行排序
- javascript - 从字符串数组创建对象数组
- typescript - 如何禁用此通知:JS/TS 分析失败。请检查 SonarLint 输出以获取更多详细信息
- node.js - 在 Ubuntu 20.04 上运行节点的 Web 服务器上增加内核 CPU 使用率
- solr - 如何检查字段是否已被索引
- json - 使用 Ansbile 解析从 API 检索到的 json 输出
- amazon-web-services - 调用 SageMaker 端点时如何将结果输出到 S3 存储桶?
- flutter - 对 2 个依赖飞镖数组进行排序
- android - 从 libs 文件夹中的 2 个本地 .aar 文件中排除重复的类
- c# - 如何在 ICandle 中转换字符串?C#