具有最少3个元素的列表的非穷举模式匹配

时间:2016-02-21 06:22:02

标签: haskell

我正试图解决希思罗机场 - 伦敦问题README。代码编译但是当我调用函数heathrow时,我收到错误,告诉我有Non-exhaustive pattern matching

heathrow :: [Int] -> [Int]
heathrow [] = []
heathrow (x : y : z : zs)
    | x < y + z = heathrow (x : zs)
    | otherwise = heathrow (z : y : zs)

我做错了什么?看起来每个案例都有所涉及。

2 个答案:

答案 0 :(得分:1)

可以通过询问GHC来回答这个问题:只需启用警告(R version 3.2.2 (2015-08-14) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 7 x64 (build 7601) Service Pack 1 locale: [1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252 [3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C [5] LC_TIME=English_United Kingdom.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] leaflet_1.0.0 shiny_0.13.1 loaded via a namespace (and not attached): [1] Rcpp_0.12.3 digest_0.6.9 mime_0.4 plyr_1.8.3 R6_2.1.2 [6] xtable_1.8-2 jsonlite_0.9.19 magrittr_1.5 scales_0.3.0 tools_3.2.2 [11] htmlwidgets_0.6 munsell_0.4.3 httpuv_1.3.3 yaml_2.1.13 colorspace_1.2-6 [16] htmltools_0.3 标志就足够了。)

-Wall

最后两行显示了我们在案例中没有考虑的列表形状,即具有一个或两个元素的列表。

答案 1 :(得分:0)

那些案件怎么样?

heathrow [x]
heathrow [x, y]

[](x : y : z : xs)都不匹配。你必须匹配这些:

heathrow :: [Int] -> [Int]
heathrow []     = []
heathrow [_]    = []
heathrow [_, _] = []
heathrow (x : y : z : zs)
    | x < y + z = heathrow (x : zs)
    | otherwise = heathrow (z : y : zs)

或者,您可以使用警卫:

heathrow xs | null (drop 2 xs) = []
heathrow (x : y : z : zs)
      ...

或移动你的比赛:

heathrow :: [Int] -> [Int]
heathrow (x : y : z : zs)
    | x < y + z = heathrow (x : zs)
    | otherwise = heathrow (z : y : zs)
heathrow _ = []