understanding scala : currying

这一生的挚爱 提交于 2019-12-10 17:35:16

问题


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

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

  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?


回答1:


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 }

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.



来源:https://stackoverflow.com/questions/26108959/understanding-scala-currying

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!