[Haskell-cafe] Very Small Program
Bernie Pope
bjpop at csse.unimelb.edu.au
Thu Nov 2 01:56:23 EST 2006
On 02/11/2006, at 4:45 PM, Jason Dagit wrote:
> Hello,
>
> I just found it (in ghci and hugs) that this is a valid haskell
> program:
> let 0 = 1 in 0
>
> This program evaluates to 0 (to my surprise).
This is a weird example of a pattern binding, and it is surprising
(to me) that the syntax is valid.
Because there are no variables on the left-hand-side of the equation,
the definition is much the same as:
let _ = 1 in 0
The definition that you give suggests that we evaluate the expression
"1", then compare it
to "0", and then do nothing with the result of the comparison
(because it doesn't bind
any variables). Though it is weird, it is rather benign, since
pattern bindings are
evaluated lazily, and in this case never.
>
> I expected something similar to how this works:
> let { 1 + 1 = 3; 3 + 1 = 7 } in 1 + 1 + 1
>
> Where you get 7.
In this case you are defining the function which is bound to the
variable called "+".
>
> So, if the 0 is not used as an identifier (ie, defining a function or
> name of a value), then why doesn't this count as a parse error? And,
> why didn't I get to locally redefine it?
In the first case the definition is pattern matching against 0, and
in the second case
the definition is giving the meaning of a variable.
While numerical constants are a little bit special in Haskell (they
are overloaded),
they act much like regular data constructors. When they appear inside
a pattern,
you are matching against them, rather than re-defining them.
One would normally expect to see at least one variable inside the
pattern on the
left-hand-side of a pattern binding (otherwise what point would there
be to the
definition?). It may very well be the case that the syntax for
Haskell in the Report
requires this, but I haven't bothered to check it up. If the Report
does require at least
one variable in the pattern, it may be the case that hugs and ghc are
using a slightly
more liberal interpretation of the grammar. Or it could be the case
that the Haskell
Report does in fact allow such pointless, but benign pattern bindings.
Perhaps you could chase this up and see what the Report really does
require?
Cheers,
Bernie.
More information about the Haskell-Cafe
mailing list