Haskell中tails函数非穷尽模式问题求助
tails Function Hey there! Let's break down why you're hitting that Non-exhaustive patterns error and fix your tails function step by step.
The Root of the Problem
Looking at your code:
tails :: [Char] -> [[Char]] tails (x:xs) | length (x:xs) == 0 = [""] | otherwise = (x:xs) : tails xs
You've only defined a pattern for non-empty lists (x:xs), but Haskell has no idea what to do when you pass an empty list []—that's exactly what the Non-exhaustive patterns error is telling you.
On top of that, the guard length (x:xs) == 0 will never be true! The x:xs syntax represents a list with at least one element (x), so its length can never be 0. That branch is completely unreachable.
The Fixed Implementation
We just need to add a pattern to handle the empty list case, and we can simplify the rest since the useless guard isn't needed:
tails :: [Char] -> [[Char]] tails [] = [""] -- Handle empty input first tails (x:xs) = (x:xs) : tails xs
How This Works
- When you pass an empty list
[], we directly return[""]—this covers the final empty string in your example. - For any non-empty list
x:xs, we take the full listx:xsas the first element of our result, then recursively calltails xsto get all the shorter tails, and prepend our full list to that result.
Testing this with your example:tails "abc" will correctly return ["abc", "bc", "c", ""]—perfect match for what you want!
Bonus: A More Generic Version
If you want this function to work with any list type (not just [Char]), you can rewrite it like this:
tails :: [a] -> [[a]] tails [] = [[]] tails xs = xs : tails (tail xs)
This does the same job, but works for lists of numbers, booleans, or any other type you can think of.
内容的提问来源于stack exchange,提问作者user376127

