本文介绍了Haskell处理负参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试对两个值求和,其中只有一个为负,例如 -1 2 :

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)而不是-1.解析器将解释您键入的(-)体(1 2).换句话说,它尝试从躯体中减去(1 2).这不起作用,因为减法不接受Float-> Float-> Float.

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.

您想要(并希望发生)的是让haskell将-作为1上的一元运算符进行评估,其优先级高于函数应用程序.这将与haskell正常工作的方式背道而驰.将(-1)解释为(取反1)已经有特殊考虑.这可能会引起一些问题,因为它是特例-在本例中,尝试咖喱-不起作用因为它不是真的-但取反.

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.

大概是为一个更广泛的特殊情况而设计的-会导致经验丰富的haskell程序员意外地出现更多行为,因此语言设计师认为这是不值得的.

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处理负参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:28