为什么 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] 表示绑定到 csone 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

通过这种方式,函数执行名称所暗示的操作,您可以根据自己的需要继续处理结果。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...