「return」ステートメントを使用しないと、次のコード(fibonacciシリーズ)の動作が異なるのはなぜですか?私は、「復帰」は必要ないと思った。Returnステートメントを使用しないSome/Noneのガベージ・値
def nthFibonacci(nth:Int): Option[Int] = {
@annotation.tailrec
def go(previousNo:Int, nextNo:Int, currentCount:Int, nth:Int):Option[Int]= {
if (currentCount == nth) Some(previousNo)
else go(nextNo,previousNo+nextNo,currentCount+1,nth)
}
if (nth<=0) None //invalid argument check
if (nth==1) Some(0) //first fibonacci
if (nth == 2) Some(1) //second fibonacci
go(1,(0+1),2,nth)
}
// n = 0,1については、私はガベージを取得しますが、NoneまたはSomeを取得する必要があります。
nthFibonacci(0) RES0:オプション[intはいくつかの(-2140540357)
nthFibonacci(2) を=:オプション[intはいくつかの(1070270178)
nthFibonacci(1) RES1 = res2:オプション[Int] = Some(1)
興味深いことに、私がコードを変更して 'return'を追加すると、コードは機能します! if(nth < = 0)戻り値なし//無効な引数チェック if(nth == 1)return some(0)// first fibonacci if(nth == 2)戻り値Some(1)// second fibonacci 行く(1、(0 + 1)、2、n番目)
nthFibonacci (0)
res0: Option[Int] = None
nthFibonacci(1)
res1: Option[Int] = Some(0)
nthFibonacci(2)
res2: Option[Int] = Some(1)
別の観察は、私がもし/他の使用している場合、コードはリターンせずに正常に動作するように見えるということです。私はどちらかのリターンを書くことを強制していますなぜか/他
if (nth<=0) None
else if (nth == 1) Some(0)
else if (nth == 2) Some(1)
else go(1,(0+1),2,nth)
nthFibonacci (0) //None
nthFibonacci(1) //Some(0)
nthFibonacci(2) //Some(1)