为什么 Haskell 查找函数会导致自定义数据类型出现非详尽模式错误?

Why is Haskell lookup function causing Non-Exhaustive pattern error on custom data type?

有人知道为什么这会导致错误 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, 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] 表示 one city (列表项)绑定到 cs -我想你想要这个 - 所以没有超过零个或一个元素的列表 - 错误告诉你。

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

这样函数就如其名,您可以继续处理您认为合适的结果。