[Haskell-beginners] Random nub questions!

ajb at spamcop.net ajb at spamcop.net
Sun Sep 14 23:05:13 EDT 2008


G'day.

Quoting Casey Rodarmor <caseyrodarmor at gmail.com>:

> Haskell is great!

Glad you think so.  It proves you have good taste. :-)

> Why is this:
>
> (+ 1)
>
> a curried invocation of the the plus operator, but this:
>
> (+ 1 2)
>
> is an error?

The plus sign is an infix operator.  Putting it in parentheses is
how you express it as a function, so if you want to apply the "plus"
function to two arguments, this is how you'd express it:

    (+) 1 2

The syntax (+ 1), on the other hand, is slightly different.  Even
though it looks like a curried function, it's actually not.  It's a
special piece of syntax called an "operator section".

If it helps, the arguments are actually the wrong way around for it
to be a curried function.  For a commutative operator like (+) this
may not make a difference, but for other operators, it does.

(>>= k), for example is not the same as ((>>=) k).   Actually, it's a
shorthand for (\m -> m >>= k).  If you wanted ((>>=) k), you'd use
(k >>=) instead.

> And in the same vein, why is this a negative number:
>
> (- 1)
>
> instead of a curried invocation of the subtraction operator?

This was a hard design decision to make.  People want to express
negation with the minus sign, but it interferes with the operator
section syntax.  The rule can be thought of as: If it looks like a
negation, then it is, otherwise it's an operator section.

> Why can't I do this:
>
>  1 `(+)` 2
>
> even if it is a little pathological?

The backquote notation is for turning _identifiers_ into operators,
not general expressions.  It would be nice to have a syntax for
turning general expressions into operators, but Haskell doesn't have
one.

> And this might be a little implementation dependent, although I'll hazard it
> anyways: Why can't I assign to things when running GHCi?

You can do this with let syntax:

     Prelude> let x = product [1..10]
     Prelude> x+2
     3628802

Cheers,
Andrew Bromage


More information about the Beginners mailing list