为什么Haskell在函数组合后不接受参数? [英] Why doesn't Haskell accept arguments after a function composition?

查看:57
本文介绍了为什么Haskell在函数组合后不接受参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到Haskell具有巡回功能,我们可以这样做:

Considering Haskell has currying functions, we can do this:

foo a b = a + b -- equivalent to `foo a = \b -> a + b`

foo 1 -- ok, returns `\b -> 1 + b`
foo 1 2 -- ok, returns 3

像在注释中一样,声明返回lambda的函数也可以正常工作.

Declaring the function returning a lambda, just like in the comment, works just fine as well.

但是当我编写这些函数时,就像这样:

But when I compose these functions, like this:

foo a b = a + b
bar x = x * x

bar . foo 1 -- ok, returns a lambda
bar . foo 1 2 -- wrong, I need to write `(bar . foo 1) 2`

然后它会导致错误.

问题是:为什么在函数组合周围需要加上括号?

The question is: why are the parentheses around the function composition necessary?

推荐答案

让我们假设您已经在GHCi中定义了以下内容:

Let's assume that you've define the following in GHCi:

λ> let foo a b = a + b
λ> let bar x = x * x

基于某些您的关注-评论,似乎您相信

bar . foo 1 2

等同于

(bar . foo 1) 2

但是,请记住,函数应用程序(空间)的优先级高于组合运算符(.);因此

However, remember that function application (space) has higher precedence than the composition operator (.); therefore

bar . foo 1 2

实际上等同于

bar . ((foo 1) 2)

现在,让我们看一下类型:

Now, let's look at the types:

  • .具有类型(b -> c) -> (a -> b) -> a -> c;它的两个参数是函数(可以组合).
  • bar具有类型Num a => a -> a,因此与.的第一个参数的类型(b -> c)兼容.
  • foo 1 2具有类型Num a => a;它是一个(多态的)数字常量, not 是一个函数,因此与.的第二个参数的类型(a -> b)不兼容.
  • . has type (b -> c) -> (a -> b) -> a -> c; its two arguments are functions (that can be composed).
  • bar has type Num a => a -> a, and is therefore compatible with the type (b -> c) of the first argument of ..
  • foo 1 2 has type Num a => a; it's a (polymorphic) numeric constant, not a function, and is therefore not compatible with the type (a -> b) of the second argument of ..

这就是为什么您在bar . foo 1 2中遇到类型错误的原因.但是,您可以做的是

That's why you're getting a type error in bar . foo 1 2. What you can do, though, is

bar $ foo 1 2

因为$运算符的类型为(a -> b) -> a -> b.请参阅 Haskell:之间的区别. (点)和$(美元符号)

because the $ operator has type (a -> b) -> a -> b. See Haskell: difference between . (dot) and $ (dollar sign)

这篇关于为什么Haskell在函数组合后不接受参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆