Haskell技术疑问:为何++运算符无法用于模式匹配(含sum函数场景)
Why can't we use ++ when defining a custom sum function?
Let's say you tried writing something like this (I've seen plenty of folks attempt this!):
sum :: [Int] -> Int sum (xs ++ ys) = sum xs + sum ys sum [] = 0 sum (x:xs) = x + sum xs
First off, the compiler will throw an error immediately because xs ++ ys isn't a valid pattern. As we covered, ++ isn't a constructor—patterns can only use constructors, variables, wildcards, or literal values.
But even if the compiler let this slide, the code would be broken beyond repair. The (xs ++ ys) pattern would match every non-empty list (since any list can be split into two parts with ++), which means the subsequent (x:xs) pattern would never run. Worse, you'd hit infinite recursion: calling sum [1,2] would match xs=[1], ys=[2], then call sum [1] + sum [2]—each of those would again match xs and ys (like sum [1] becomes sum [] + sum [1]), leading to an endless loop.
The correct way to write sum uses list constructors, which give us unambiguous, non-recursive base cases and steps:
sum :: [Int] -> Int sum [] = 0 sum (x:xs) = x + sum xs
This works because : lets us decompose the list into exactly one head and one tail every time—no ambiguity, no infinite loops, just clean, predictable logic.
内容的提问来源于stack exchange,提问作者Abhisek

