为什么 Scala 中的柯里化需要多个参数列表? [英] Why does currying in Scala need multiple parameter lists?

查看:55
本文介绍了为什么 Scala 中的柯里化需要多个参数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个需要部分应用的 2 个参数的函数,我需要将其定义为:

Suppose I have a function of 2 parameters that I need to apply partially, I need to define it as:

def f(a: Int)(b: Int) = { /* some code */ }

然后我可以将它部分应用为 def fWithA = f(a) _

And then I can apply it partially as def fWithA = f(a) _

我的问题是:为了使函数柯里化,为什么 Scala 要求使用多个参数列表声明参数?最好能够根据需要对任何函数进行柯里化.

My question is: In order to curry a function why does Scala require that the parameters are declared using multiple parameter lists? It would be preferable to be able to curry any function as desired.

推荐答案

在 Scala 中真正的"柯里化需要多个参数列表的几个原因:

A few reasons 'real' currying requires multiple parameter lists in Scala:

  • 重载.与纯函数式语言不同,在 Scala 中您可以重载方法.如果您部分应用一个函数,编译器可能无法区分您指的是哪个重载.规范将重载解析限制为第一个参数列表.

  • overloading. Unlike purely functional languages, in Scala you can overload methods. If you partially apply a function, the compiler may not be able to distinguish which overload you mean. The specification limits overloading resolution to the first parameter list.

错误信息.方法调用的参数不足"是一条非常有用(且易于理解)的错误消息.如果允许对任何方法进行柯里化,则错误消息将是必需的:但是具有许多箭头的某些函数类型"类型.

error messages. "not enough arguments for method call" is a very useful (and easy to understand) error message. If one allowed currying for any method, the error message would be "required: but "some function type with many arrows" type.

表现.在 JVM 上运行使得调用方法非常高效,而函数(通过接口调用)速度较慢.

performance. Running on the JVM makes it very efficient to call methods, while functions (going through an interface call) are slower.

这篇关于为什么 Scala 中的柯里化需要多个参数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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