如何解决为什么 Haskell 查找函数会导致自定义数据类型的非穷举模式错误?
有人知道为什么会导致错误 Non-exhaustive patterns in function getCityPopulation
吗?
type Name = String
type Coordinates = (Int,Int)
type Pop = Int
type TotalPop = [Pop]
type City = (Name,(Coordinates,TotalPop))
testData :: [City]
testData = [("New York City",((1,1),[5,4,3,2])),("Washingotn DC",((3,3),[3,2,1,1])),("Los Angeles",((2,2),[7,7,5]))]
getCityPopulation :: [City] -> Name -> Int -> Maybe (Coordinates,TotalPop)
getCityPopulation [] nameIn yearIn = error "Can't be empty"
getCityPopulation [cs] nameIn yearIn
| nameIn == "" = error "Input City name"
| yearIn == 0 || yearIn < 0 = error "invalid year"
| otherwise = lookup nameIn [cs]
如您所见,我已尝试添加一个案例,说明当任何参数可能为空或仅对查找函数无效时。还能是什么?
此外,我知道 yearIn
变量目前是多余的,稍后将适用于预期的函数用途,即获取 TotalPop 列表的 yearIn
元素。
在此先感谢您提供的所有帮助:)
解决方法
[cs]
表示绑定到 cs
的 one city (list-item) 列表 - 我想你想要这个 - 所以有对于包含超过零个或一个以上元素的列表,情况并非如此 - 错误告诉您这一点。
getCityPopulation :: [City] -> Name -> Int -> Maybe (Coordinates,TotalPop)
getCityPopulation [] nameIn yearIn = error "Can't be empty"
getCityPopulation cs nameIn yearIn
| nameIn == "" = error "Input City name"
| yearIn == 0 || yearIn < 0 = error "invalid year"
| otherwise = lookup nameIn cs
现在第 3 个条目匹配 any 列表并将其绑定到 cs
但与之前的情况一样,已经捕获的空列表 cs
将至少有一个元素。>
顺便说一句:我认为您不需要这个 - 为什么在返回 Maybe
时抛出错误(程序崩溃)? - 除了检查之外,您也永远不会使用 yearIn
。
我只推荐
tryGetCityPopulations :: [City] -> Name -> Maybe TotalPop
tryGetCityPopulations cs nameIn = snd <$> lookup nameIn cs
通过这种方式,函数执行名称所暗示的操作,您可以根据自己的需要继续处理结果。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。