You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell中tails函数非穷尽模式问题求助

Fixing the Non-exhaustive Patterns Error in Your Haskell 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 list x:xs as the first element of our result, then recursively call tails xs to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:32:26