Haskell 点运算符
我尝试在 Haskell 中开发一个简单的平均函数。 这似乎有效:
lst = [1, 3]
x = fromIntegral (sum lst)
y = fromIntegral(length lst)
z = x / y
但为什么以下版本不起作用?
lst = [1, 3]
x = fromIntegral.sum lst
y = fromIntegral.length lst
z = x / y
I try to develop a simple average function in Haskell.
This seems to work:
lst = [1, 3]
x = fromIntegral (sum lst)
y = fromIntegral(length lst)
z = x / y
But why doesn't the following version work?
lst = [1, 3]
x = fromIntegral.sum lst
y = fromIntegral.length lst
z = x / y
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你被 haskell 的运算符优先级规则绊倒了,这令人困惑。
当你编写
Haskell 时,它会看到与以下内容相同:
你本来想写的是:
You're getting tripped up by haskell's precedence rules for operators, which are confusing.
When you write
Haskell sees that as the same as:
What you meant to write was:
.
(组合)的优先级低于函数应用,因此被解释为
错误,因为
sum lst
不是函数。.
(composition) has a lower precedence than function application, sois interpreted as
which is wrong since
sum lst
is not a function.我只是想添加“$来救援!”:
它具有最低的优先级,并且它的存在是为了避免过多的括号级别。请注意,与 (.) 不同,它不进行函数组合,而是计算右侧的参数并将其传递给左侧的函数。类型说明了一切:
I just wanted to add "$ to the rescue!":
It has the lowest precedence and it's there to avoid too many parenthesis levels. Note that unlike (.), it doesn't do function composition, it evaluates the argument to the right and pass it to the function on the left. The type says it all: