Scala有智能编译器吗? [英] Scala has smart compiler?

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

问题描述

我做了递归函数,就像

require : L (List[Int])

L模式匹配


  1. 无=> Thread.dumpStack()

  2. x :: xs => print(x)+ function(xs)

  1. Nil => Thread.dumpStack()
  2. x :: xs => print(x) + function(xs)




def function(L : List[Int]) {
    L match {
        case Nil => Thread.dumpStack()
        case x :: xs => print(x + " "); function(xs)
    }
}

val l =(1至5 ).toList //
function(l)

val l = (1 to 5).toList // function(l)

所以我认为此函数在堆栈帧中存在n次,但它发生一次,我认为此函数已经找到 Nil 并打印出异常 Thread.dumpStack

So I think this function in the stack frame n times, but it occurs one time, I think this function has already found Nil and print out exception Thread.dumpStack.

scala编译器是智能的还是其他?

Is scala compiler smart or other else?

推荐答案

您正在观察尾递归:从一次迭代到下一次迭代没有什么可存储的,因此编译器实质上将递归转换为while循环。 (所以,是的,编译器很聪明。)

You are observing tail recursion: there is nothing to store from one iteration to the next, so the recursion is essentially turned into a while loop by the compiler. (So, yes, the compiler is smart in that way.)

这篇关于Scala有智能编译器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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