[英]understanding scala : currying
I recently started learning Scala and came across currying. 我最近开始学习Scala并且遇到了currying。 From an answer in this post , this code snippet
从这篇文章中的答案,这段代码片段
def sum(a: Int)(b: Int) = a + b
expands out to this 扩展到这个
def sum(a: Int): Int => Int = b => a + b
Then I saw a snippet from scala-lang , which shows it's possible to write something like this to emulate a while loop 然后我看到scala-lang的一个片段,它显示可以写这样的东西来模拟一个while循环
def whileLoop (cond : => Boolean) (body : => Unit) : Unit = {
if (cond) {
body
whileLoop (cond) (body)
}
}
Out of curiosity, I tried to expand this out, and got this 出于好奇,我试图扩展它,并得到了这个
def whileLoop2 (cond : => Boolean) : (Unit => Unit) =
(body : => Unit) =>
if (cond) {
body
whileLoop2 (cond) (body)
}
But there seems to be some syntax that I'm missing because I get an error 但是我似乎缺少一些语法,因为我收到错误
error: identifier expected but '=>' found.
(body : => Unit) =>
^
What is the proper way to expand out the emulated while loop? 扩展模拟while循环的正确方法是什么?
The tricky part is dealing with the parameterless function or "thunk" type => Unit
. 棘手的部分是处理无参数函数或“thunk”type
=> Unit
。 Here is my version: 这是我的版本:
def whileLoop2 (cond: => Boolean): (=> Unit) => Unit =
body =>
if (cond) {
body
whileLoop2 (cond)(body)
}
var i = 5
val c = whileLoop2(i > 0)
c { println(s"loop $i"); i -= 1 }
It appears that you can annotate the return type with (=> Unit) => Unit
, but you cannot annotate (body: => Unit)
, so you have to rely on the type inference here. 看来你可以用
(=> Unit) => Unit
来注释返回类型,但是你不能注释(body: => Unit)
,所以你必须在这里依赖类型推断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.