[Haskell-cafe] An interesting curiosity

Andrew Coppin andrewcoppin at btinternet.com
Thu Sep 18 14:59:51 EDT 2008


I'm currently reading a C++ tutorial. (Don't ask!)

Of course, C++ is that crazy language where *assignment* is actually an 
*operator*. Sick, sick people...

The tutorial pointed out that "x = 4" is a legal assignment, but "4 = x" 
is not. "Obviously that would be silly."

Now it occurs to me... in Haskell, "4 = x" is actually a perfectly legal 
thing to say. (!) It's pretty pointless, but it's legal. For example:

  foo x = let 4 = x in 2*x

which, as best as I can tell, does exactly the same thing as (2*).

In a similar vein, one might write

  foo x = do
    let 4 = x
    return (2*x)

which also does more or less the same as (return).

However, consider the following:

  foo :: Int -> Maybe Int
  foo x = do
    4 <- return x
    return (2*x)

This, it turns out, is an extremely odd way of checking whether x == 4.

All of this works of course because in Haskell, "=" is not an 
assignment, it's a definition, and the RHS is not a variable, it's a 
pattern. And "4" is a perfectly legitimate pattern. Now, if only I could 
find a use for all this that borders on "useful"...! ;-)



More information about the Haskell-Cafe mailing list