理解Scala:柯里化 [英] understanding scala : currying

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

问题描述

我最近开始学习 Scala 并遇到了柯里化.从这个帖子中的答案,这段代码片段

I recently started learning Scala and came across currying. From an answer in this post, this code snippet

def sum(a: Int)(b: Int) = a + b

扩展到这个

def sum(a: Int): Int => Int = b => a + b

然后我看到了 scala-lang 的片段,这表明可以编写这样的东西来模拟 while 循环

Then I saw a snippet from scala-lang, which shows it's possible to write something like this to emulate a while loop

  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) => 
        ^

扩展模拟 while 循环的正确方法是什么?

What is the proper way to expand out the emulated while loop?

推荐答案

棘手的部分是处理无参数函数或thunk"类型 =>单位.这是我的版本:

The tricky part is dealing with the parameterless function or "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 }

看来您可以使用 (=> Unit) => 注释返回类型.Unit,但是你不能注释(body: => Unit),所以你必须依赖这里的类型推断.

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.

这篇关于理解Scala:柯里化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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