[Haskell-cafe] Newbie question: the need for parentheses
Jules Bean
jules at jellybean.co.uk
Tue Jan 8 16:48:01 EST 2008
Fernando Rodriguez wrote:
>
> Hi,
>
> I have this function that sums up a list of numbers:
>
> suma [] = 0
> suma (h:t) = h + suma t
>
> However, why do I need the parenthes in the second clause? What does the
> compiler think I'm trying to do when I type
> suma [] = 0
> suma h:t = h + suma t
Definitions are parsed in very much the same way as expressions. In
principle they don't need to be, but it makes the language more uniform
if they are.
If you wrote "suma h:t" as an expression, it would mean "(suma h) : t",
because function application "binds tighter" than any infix operator.
So, as a definition:
suma h : t = h + suma t
looks to the compiler like an attempt to redefine the operator ':',
except that the left parameter is "suma h", which looks like a function
application, and that's not allowed in a definition.
[it also doesn't make sense because ':' is actually a constructor not
any old operator. But that turns out not to be the key problem here]
Note that you can define operators directly infix, e.g.:
a * b = multiply a b
...and if I try to do that with something like 'suma' on the left...
suma a * b = multiply a b
...I get the same error (parse error in pattern, in GHC).
Hope that helps,
Jules
More information about the Haskell-Cafe
mailing list