加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala中的curried函数

发布时间:2020-12-16 18:38:36 所属栏目:安全 来源:网络整理
导读:我有下一个方法的定义: def add1(x: Int,y: Int) = x + ydef add2(x: Int)(y: Int) = x + y 第二个是第一个的curried版本.然后,如果我想部分应用第二个函数,我必须写val res2 = add2(2)_.一切都好.接下来我想要添加add1函数.我写 val curriedAdd = (add1 _)
我有下一个方法的定义:

def add1(x: Int,y: Int) = x + y

def add2(x: Int)(y: Int) = x + y

第二个是第一个的curried版本.然后,如果我想部分应用第二个函数,我必须写val res2 = add2(2)_.一切都好.接下来我想要添加add1函数.我写

val curriedAdd = (add1 _).curried

我是对的,curriedAdd与add2类似吗?
但是当我尝试以这样的方式部分应用curriedAdd时,val resCurried = curriedAdd(4)_我得到了编译错误.然后我修复它

val resCurried = curriedAdd(4)

为什么Functions.curried的结果与添加函数的curried版本(来自add2)不同?

解决方法

首先curriedAdd与add2 _相同而不是add2. add2只是一种方法.

scala> curriedAdd
res52: Int => (Int => Int) = <function1>

scala> add2 _
res53: Int => (Int => Int) = <function1>

关于第二个问题.我认为以下是原因.干

scala> val i = curriedAdd(23)
i: Int => Int = <function1>

scala> i _
res54: () => Int => Int = <function0>

scala> curriedAdd(23) _
<console>:10: error: _ must follow method; cannot follow Int => Int
              curriedAdd(23) _

curriedAdd(23)_不起作用.让我们看看scala手册(§6.7) –

The expression e _ is well-formed if e is of method type or if e is a
call-by-name parameter. If e is a method with parameters,e _
represents e converted to a function type by eta expansion (§6.26.5).
If e is a parameterless method or call-by-name parameter of type =>T,
e _ represents the function of type () => T,which evaluates e when
it is applied to the empty parameterlist ().

请记住,它仅评估它是方法还是按名称调用参数.在curriedAdd(23)_中,它不评估curriedAdd(23),但检查它是方法还是按名称调用.它不是方法,也不是按名称调用参数.

它不是名字,因为by-name是变量的属性.在评估curriedAdd(23)之后,你会得到一个by-name参数,但curriedAdd(23)本身并不是一个名字变量.因此错误(理想情况下编译器应该转换它).请注意以下工作原理:

scala> curriedAdd(23)
res80: Int => Int = <function1>

scala> res80 _
res81: () => Int => Int = <function0>

上面的工作原因是res80 _,这里你将_应用于一个call-by-name参数,从而进行转换.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读