Haskell 点运算符

发布于 2024-09-01 17:13:33 字数 273 浏览 13 评论 0原文

我尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

檐上三寸雪 2024-09-08 17:13:33

你被 haskell 的运算符优先级规则绊倒了,这令人困惑。

当你编写

x = fromIntegral.sum lst

Haskell 时,它会看到与以下内容相同:

x = fromIntegral.(sum lst)

你本来想写的是:

x = (fromIntegral.sum) lst

You're getting tripped up by haskell's precedence rules for operators, which are confusing.

When you write

x = fromIntegral.sum lst

Haskell sees that as the same as:

x = fromIntegral.(sum lst)

What you meant to write was:

x = (fromIntegral.sum) lst
若言繁花未落 2024-09-08 17:13:33

.(组合)的优先级低于函数应用,因此

fromIntegral.sum lst

被解释为

fromIntegral . (sum lst)

错误,因为 sum lst 不是函数。

. (composition) has a lower precedence than function application, so

fromIntegral.sum lst

is interpreted as

fromIntegral . (sum lst)

which is wrong since sum lst is not a function.

无言温柔 2024-09-08 17:13:33

我只是想添加“$来救援!”:

x = fromIntegral $ sum lst
y = fromIntegral $ length lst

它具有最低的优先级,并且它的存在是为了避免过多的括号级别。请注意,与 (.) 不同,它不进行函数组合,而是计算右侧的参数并将其传递给左侧的函数。类型说明了一切:

($) :: (a -> b) -> a -> b
(.) :: (b -> c) -> (a -> b) -> a -> c

I just wanted to add "$ to the rescue!":

x = fromIntegral $ sum lst
y = fromIntegral $ length lst

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:

($) :: (a -> b) -> a -> b
(.) :: (b -> c) -> (a -> b) -> a -> c
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文