[Haskell-cafe] map (-2) [1..5]
Jared Updike
jupdike at gmail.com
Thu Aug 17 11:49:37 EDT 2006
> I'd have thought it would have been simpler to just make the rule that -2
> (no spaces between '-' and '2') would be a single lexeme
I'd have thought so too, until I implemented a parser with exponentiation.
It is easy to get confused and make a parser that is too eager to include
the minus sign as part of a numeric literal instead of as subtraction
or unary negation (all you parser-with-exponentiation-implementers out
there, pay attention!). And since many
programming languages (specifically C) don't have syntax for
exponentation as an infix operator (nothing authoritative to copy
precedence from), I had to implement this myself, get confused and see
that it was so---(I tried making the literal include the minus sign if
there was no space). I never noticed this before because in a C-like
language:
-4*2 is the same whether parsed as
(-4)*2 or -(4*2)
but
-4^2 is not the same whether parsed as
(-4)^2 or -(4^2) (the correct version)
Basically, before someone argues this with me,
-4^2 should parse the same as
- 4^2 which should be the same thing as
0 - 4^2
(you don't want -4^2 and 0-4^2 giving different results, no matter
how much you think whitespace belongs around operators)
Math follows these same rules but it's slightly harder to get confused
because of the way exponentiation is written by superscripting. See
http://mathforum.org/library/drmath/view/55709.html and
http://mathforum.org/library/drmath/view/53240.html.
I thought this was surprising, that parsing the minus sign into
lexemes would cause such confusion, but it is born out in many places
(Python, Frink (http://futureboy.homeip.net/frinkdocs/FrinkApplet.html),
etc.)
(Note: this email isn't about Haskell specifically and I'm sure issues
with the minus sign in Haskell are more confusing than this; this is
purely about parsing a C-like langauge extended with exponentionation
and how including the minus sign in the literal is dangerous in
conjuntion with exponentiation.)
Jared.
--
http://www.updike.org/~jared/
reverse ")-:"
More information about the Haskell-Cafe
mailing list