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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:20:14