Haskell:函数中的非穷举模式(简单函数) [英] Haskell: Non-exhaustive patterns in function (simple functions)
问题描述
对于该函数的第一个和第三个版本为什么会出现此错误,而第二个定义却能正常工作,我感到困惑.
I am confused as to why the 1st and 3rd versions of this functions give this error whereas the second definition works fine.
-- head and tail
third :: [a] -> a
third [a] = head (tail (tail[a]))
-- Pattern matching
third2 :: [a] -> a
third2 (_:_:x:_) = x
-- List indexing
third3 :: [a] -> a
third3 [a] = [a]!!2
预先感谢
推荐答案
奇怪的是,第二个没有抱怨非详尽无遗模式,因为 third2
将不匹配长度为零,一或两个的列表. third
和 third3
函数抱怨,因为 [a]
不是变量,这是一种模式.将 [a]
还原为(a:[])
,所以您可以将它们写为
That is odd that the second one does not complain about non-exhaustive
patterns, since third2
will not match lists of length zero, one, or two.
The third
and third3
functions complain because [a]
is not a variable,
it is a pattern. [a]
desugars to (a:[])
, so you could have written them as
third (a:[]) = head (tail (a:[]))
third3 (a:[]) = (a:[]) !! 2
这两个都不起作用,因为它们是单个元素列表.我怀疑你想要的是什么
Neither of which will work, as those are single element lists. I suspect what you want is
third a = head (tail a)
third3 a = a !! 2
这篇关于Haskell:函数中的非穷举模式(简单函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!