Scala函数定义参数列表中的不同括号样式 [英] Different brackets style on Scala function definition parameter list

查看:902
本文介绍了Scala函数定义参数列表中的不同括号样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala中以下两个函数定义的区别:
$ b <1> def sum(f:Int => Int) (a:Int,b:Int):Int = {<代码移除> }



<2> def sum(f:Int => Int,a:Int,b:Int) :Int = {<代码移除> }





SBT的控制台REPL为它们提供了不同的值,他们是不同的:
$ b $ p sum:(f:Int => Int,a:Int,b:Int)Int $ b

sum:(f:Int => Int)(a:Int,b:Int)Int 您可以在另一次提供 a b



例如,如果您知道您想在当前方法中使用的函数,但尚未知道参数,则可以这样使用它:

  def mySum(v:Int):Int = v + 1 
val newsum = sum(mySum)_

此时, newsum 是一个函数, code> Int s并返回一个 Int



在上下文中总结它似乎没有太大意义;然而,我曾经有很多次想要根据我现在知道的东西返回不同的算法部分程序,但不知道(或有权访问)参数。



Currying会为您购买该功能。


What is the difference of the following two function definitions in Scala:

1) def sum(f: Int => Int)(a: Int, b: Int): Int = { <code removed> }

2) def sum(f: Int => Int, a: Int, b: Int): Int = { <code removed> }

?

SBT's console REPL gives different value for them so looks if they are somehow different:

sum: (f: Int => Int, a: Int, b: Int)Int

sum: (f: Int => Int)(a: Int, b: Int)Int

解决方案

The first definition is curried, so that you can provide a and b at another time.

For instance, if you know the function you want to use in the current method, but don't yet know the arguments, you can use it so:

def mySum(v: Int): Int = v + 1
val newsum = sum(mySum) _

At this point, newsum is a function that takes two Ints and returns an Int.

In the context of summing it doesn't seem to make much sense; however, there have been plenty of times I've wanted to return different algorithms for parts of a program based upon something I know now, but don't know (or have access to) the parameters yet.

Currying buys you that feature.

这篇关于Scala函数定义参数列表中的不同括号样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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