Haskell自定义枚举类型构造算术序列为何需额外空格?
.. for Custom Enum Types in Haskell Great question! This boils down to two key parts of Haskell's syntax: how the lexer parses code into tokens, and the difference between numeric literals and constructor identifiers. Let's break it down step by step:
1. Numeric literals work with .. without spaces
When you write [1..5], Haskell's lexer (the component that turns your code into meaningful chunks for the compiler) recognizes:
1as an integer literal token..as the special range syntax token5as another integer literal
This works because a numeric literal followed by two dots isn't a valid standalone token. 1. isn't a valid floating-point literal (those require digits after the dot), so the lexer doesn't try to combine 1 and the first dot into a single token. It correctly splits them into 1 and ...
2. Constructor identifiers + .. get misinterpreted without spaces
Take your custom enum example: data Suit = Club | Diamond | Heart | Spade deriving (Show, Enum).
If you tried writing [Club..Diamond] (no spaces), Haskell's lexer would split this into four separate tokens:
Club(the constructor identifier).(the function composition operator).(another function composition operator)Diamond(another constructor identifier)
The compiler would then interpret this as Club . . Diamond—a valid but totally unintended expression using function composition. It’s equivalent to Club . (. Diamond), meaning "compose the Club constructor with a function that takes an argument and composes it with Diamond". That’s nothing like the range you wanted!
By adding a space between Club and .. (like [Club .. Diamond]), you tell the lexer to treat Club as a standalone token and .. as the special range syntax token. The parser then correctly recognizes this as a range over your Enum type.
Quick summary
- Numeric literals can’t form a valid token with
.., so the lexer splits them correctly automatically. - Constructor identifiers followed by
.get interpreted as function composition unless you add a space to separate the constructor from the range syntax.
内容的提问来源于stack exchange,提问作者MicMac

