2016-08-18 24 views
0

我對Scala很新。我試着從主傳遞abs,fact,fib的順序中調用println中的formatResult 3次。在用戶定義函數formatResult上調用println從main執行3次,但執行順序不同

但輸出顯示不同的執行順序 - 事實上,FIB,ABS

/* * MyModule.scala/

object MyModule { 

    def abs(n: Int): Int = 
     if(n < 0) 
      -n 
     else 
      n 

    def fact(n: Int): Int = { 
     def go(n: Int, acc: Int): Int = { 
      if(n <= 1) 
       acc 
      else 
       go(n - 1, n * acc) 
     } 

     go(n, 1) 
    } 

    def fib(n: Int): Int = { 
     def loop(n: Int, prev: Int, curr: Int): Int = { 
      if(n == 0) 
       prev 
      else 
       loop(n - 1, curr, prev + curr) 
     } 

     loop(n, 0, 1) 
    } 

    private def formatResult(fName: String, placeholder: String, n: Int, f: Int => Int) = { 
     val msg = "The %s %s %d is %d" 
     msg.format(fName, placeholder, n, f(n)) 
    } 

    def main(args: Array[String]): Unit = 

     println(formatResult("absolute value", "of", -10, abs)) 
     println(formatResult("factorial", "of", 5, fact)) 
     println(formatResult("fibonacci number", "at index", 8, fib)) 
} 

/*輸出*/

The factorial of 5 is 120 
The fibonacci number at index 8 is 21 
The absolute value of -10 is 10 

可能有人請向我解釋這個?

回答

2

您的主要方法代碼不是由大括號包圍。所以你的主要方法變成如下:

def main(args: Array[String]): Unit = 

println(formatResult("absolute value", "of", -10, abs)) 

其他兩個打印行是在設置對象時執行的。所以他們在主要方法被調用之前運行。以下內容將正常工作:

def main(args: Array[String]): Unit = { 

    println(formatResult("absolute value", "of", -10, abs)) 
    println(formatResult("factorial", "of", 5, fact)) 
    println(formatResult("fibonacci number", "at index", 8, fib)) 
} 
相關問題