Skip to content

Instantly share code, notes, and snippets.

@yutaono
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yutaono/c862584dc0b4e95ed876 to your computer and use it in GitHub Desktop.
Save yutaono/c862584dc0b4e95ed876 to your computer and use it in GitHub Desktop.
scala tail recursive optimization
  • Main.scala
import scala.annotation.tailrec

object Main extends App {
  def f(a: Int): Int = {
    a match {
      case x if x <= 1 => 1
      case x => x * f(x - 1)
    }
  }

  @tailrec
  def g(a: Int, s: Int): Int = {
    a match {
      case x if x <= 1 => s
      case x => g(x - 1, s * (x - 1))
    }
  }
}
$ scalac Main.scala
$ jad Main\$.class
Parsing Main$.class... Generating Main$.jad
  • Main$.jad
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name:   Main.scala

import scala.App;
import scala.Function0;
import scala.collection.mutable.ListBuffer;

public final class Main$
    implements App
{

    public long executionStart()
    {
        return executionStart;
    }

    public String[] scala$App$$_args()
    {
        return scala$App$$_args;
    }

    public void scala$App$$_args_$eq(String x$1[])
    {
        scala$App$$_args = x$1;
    }

    public ListBuffer scala$App$$initCode()
    {
        return scala$App$$initCode;
    }

    public void scala$App$_setter_$executionStart_$eq(long x$1)
    {
        executionStart = x$1;
    }

    public void scala$App$_setter_$scala$App$$initCode_$eq(ListBuffer x$1)
    {
        scala$App$$initCode = x$1;
    }

    public String[] args()
    {
        return scala.App.class.args(this);
    }

    /**
     * @deprecated Method delayedInit is deprecated
     */

    public void delayedInit(Function0 body)
    {
        scala.App.class.delayedInit(this, body);
    }

    public void main(String args[])
    {
        scala.App.class.main(this, args);
    }

    public int f(int a)
    {
        int i = a;
        switch(i)
        {
        default:
            return i > 1 ? i * f(i - 1) : 1;
        }
    }

    public int g(int a, int s)
    {
        do
        {
            int i = a;
            switch(i)
            {
            }
            if(i <= 1)
                return s;
            s *= i - 1;
            a = i - 1;
        } while(true);
    }

    private Main$()
    {
        scala.App.class.$init$(this);
    }

    public static final Main$ MODULE$ = this;
    private final long executionStart;
    private String scala$App$$_args[];
    private final ListBuffer scala$App$$initCode;

    static
    {
        new Main$();
    }
}
@yutaono
Copy link
Author

yutaono commented Jul 28, 2015

f は末尾再帰最適化されていないが、g はされている

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment