Haskell - 使用list的函数出现“非详尽模式”错误

时间:2015-03-28 13:02:27

标签: list haskell non-exhaustive-patterns

我试图在haskell中创建一个函数来知道列表列表中的所有元素是否具有相同的长度。 (我在之前的帖子中搜索过答案,但没有一个有效)。

sameLength :: [[t]] -> String
sameLength [] = "Empty list"
sameLength [[items]]
    | and $ map (\x -> length x == (length $ head [[items]])) [[items]] = "Same length"
    | otherwise = "Not the same length"

问题在于它不起作用:

*Main> :l test.hs
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> sameLength []
"Empty list"
*Main> sameLength [[1,2],[3,4]]
"*** Exception: test.hs:(2,1)-(5,39): Non-exhaustive patterns in function sameLength

*Main> sameLength [[1,2]]
"*** Exception: test.hs:(2,1)-(5,39): Non-exhaustive patterns in function sameLength

我真的不知道问题出在哪里。它处理参数是空列表而不是空列表的情况。我错了吗 ?我错过了什么吗?

感谢您的帮助:)

2 个答案:

答案 0 :(得分:4)

模式[x]匹配仅包含一个项目x的列表。因此,模式[[items]]匹配包含单个项目的单个列表。你想要的是匹配第二种情况下的所有非空列表。但由于空列表已被匹配,通过消除,您只需要匹配尚未匹配的任何内容。

sameLength :: [[t]] -> String
sameLength [] = "Empty list"
sameLength items = -- Code here

答案 1 :(得分:3)

你这里有太多[..]

sameLength [[items]] 

(正如Silvio解释得非常好) - 尝试

sameLength items 

代替。

此外,a == a,你不必检查头部的长度是否与头部的长度相同(当然),所以我建议这样做:

sameLength :: [[a]] -> Bool
sameLength []     = True
sameLength (h:tl) = all ((length h ==) . length) tl

因为我认为Bool结果更有用和自然

这是如何工作的?

all获取谓词和列表,并检查谓词是否适用于列表的每个元素 - 因此(length h ==) . length = \xs -> length h == length xs作为谓词检查给定列表xs是否具有相同的长度作为头条列表h - 所以由于上面的评论,您只需要使用尾部列表tl

进行检查

备注

你可以争辩说空列表的所有元素是否应该具有相同的长度 - 但我认为答案应该是肯定的;)

实施例

Prelude> sameLength [[1,2],[3,4]]
True
Prelude> sameLength [[1,2],[3,4,5]]
False
Prelude> sameLength [[1,2]]
True
Prelude> sameLength []
True

以防您关注性能

(或者你不喜欢无点风格)

sameLength :: [[a]] -> Bool
sameLength []     = True
sameLength (h:tl) = let l = length h
                    in all (\xs -> length xs == l) tl