gpt4 book ai didi

haskell - 功能中的非详尽模式

转载 作者:行者123 更新时间:2023-12-03 11:09:23 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Better exception for non-exhaustive patterns in case

(2 个回答)


5年前关闭。




我的这段代码有问题,它应该计算字符串中同一字母的最长子字符串,但是有一个错误:

*** Exception: test.hs:(15,0)-(21,17): 
Non-exhaustive patterns in function countLongest'

我知道这是错误类型的问题,但我不知道错误在哪里,或者如何查找或调试它
countLongest :: (Eq a) => [a] -> Int
countLongest' :: (Eq a) => Int -> Int -> [a] -> Int

countLongest a = countLongest' 0 0 a
countLongest' n max (y:x:ys)
| y == x = countLongest' (n+1) max (x:ys)
| n > max = countLongest' 0 (n) (x:ys)
| otherwise = countLongest' 0 (max) (x:ys)
countLongest' n max []
| n > max = n
| otherwise = max

最佳答案

看起来您错过了只有一个元素列表的情况:

countLongest' n max (y:ys)
| ... etc. ...
| otherwise = ....

这是一个与您类似的人为示例:
f [] = 3         -- matches an empty list
f (a:b:bs) = 4 -- matches a list with at least two elements

例子:
Prelude> :load myfile.hs 
[1 of 1] Compiling Main ( myfile.hs, interpreted )
Ok, modules loaded: Main.
*Main> f [3]
*** Exception: myfile.hs:(3,0)-(4,13): Non-exhaustive patterns in function f

*Main> f []
3
*Main> f [1,2,3,4,5]
4
*Main>

所以它在列表中有 0 个和 2 个元素时成功,但当只有一个元素时失败。

请注意,此行为是 不是 列表独有。这是一个使用 Maybe 的示例:
g :: Maybe x -> x
g (Just x) = x

例子:
*Main> g (Just 4)
4
*Main> g Nothing
*** Exception: myfile.hs:6:0-13: Non-exhaustive patterns in function g

发生这种情况是因为 Maybe 有两个构造函数, Just <something>Nothing .我们没有为 Nothing 提供案例,所以当我们将它传递给 g ,它没有工作!

查看 this question及其有关从编译器获得一点帮助的信息的答案。我遵循了第一个答案的建议,当我加载我的示例时,发生了这样的事情:
prompt$ ghci -fwarn-incomplete-patterns

Prelude> :load myfile.hs
[1 of 1] Compiling Main ( myfile.hs, interpreted )

myfile.hs:3:0:
Warning: Pattern match(es) are non-exhaustive
In the definition of `f': Patterns not matched: [_]

myfile.hs:6:0:
Warning: Pattern match(es) are non-exhaustive
In the definition of `g': Patterns not matched: Nothing
Ok, modules loaded: Main.

凉爽的!编译器非常聪明!

关于haskell - 功能中的非详尽模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8435575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com