Haskell handling negative parameters

2019-08-14 04:54发布

问题:

Trying to sum two values, with only one of them negative, such as -1 and 2:

soma :: Float -> Float -> Float
soma x1 x2 = x1 + x2

The result in an error; WHY?

<interactive>:10:6:
No instance for (Num (Float -> Float -> Float))
  arising from a use of `-'
Possible fix:
  add an instance declaration for (Num (Float -> Float -> Float))
In the expression: soma - 1 2
In an equation for `it': it = soma - 1 2

回答1:

You should use (-1) instead of - 1. The parser interprets what you typed as (-) soma (1 2). In other words, it tried to subtract (1 2) from soma. Which doesn't work because subtract doesn't accept a Float -> Float -> Float.

What you would like (and expected to happen) was for haskell to evaluate the - as a unary operator on 1, with higher precedence than the function application. This would be contrary to the way haskell normally works. There already is special consideration for (-1) being interpreted as (negate 1). This can cause some problems, by virtue of being a special case - in the example trying to curry the - doesn't work because it isn't really -, but negate.

Presumably an even broader special case carved out for - would lead to even more behavior unexpected by experienced haskell programmers and so the language designers decided it wasn't worth it.



标签: haskell