0

関数型プログラミングの学習を始めたばかりで、頭を悩ませています。これは私が現在持っているものです。なぜ機能しないのかはわかっていますが (comb は不変であるため)、やりたいことを実行する方法を考えることができないようです。

  def countChange(money: Int, coins: List[Int]): Int = {
    def rCountChange(money: Int, coins: List[Int], comb: Int): Int = {
      if (money >= coins(0)) rCountChange(money - coins(0), coins, comb)
      if (money == 0) comb + 1 //base case sequence found
      if (coins.isEmpty) comb //base case sequence not found
      rCountChange(money, coins tail, comb)
    }
    rCountChange(money, coins, 0)

  }

配列を作成してそれに追加し、結果を .length にすることを考えましたが、可変変数を使用して回避するためのギミックな方法のようです。

櫛 + 1 を println("combination found") に置き換えると、見つかった適切な量の基本ケースが出力されるので、すべての可能性を適切に反復していると確信しています。

ありがとう

4

2 に答える 2

2

背景を説明すると、この質問は、Coursera の Odersky のクラスの課題の 1 つに対するものです。私はたまたま彼のテストに合格するソリューションを持っているので、完全な実装を提供することなくヒントを提供したいと思います。現時点では、Vlad の回答も alex23 の回答もテストに合格していません。

重要なのは、基本ケースに遭遇するまで、2 つの方向で再帰を行うことです。また、基本ケースに到達しない限り、各ケースはどちらか一方だけでなく、その繰り返しの合計を返す必要があります。

于 2013-04-04T17:18:36.050 に答える
1

elseの末尾に がありません。if代わりに を使用できますreturn

そのままでは、関数はケースにヒットした後も評価を続け、意図したとおりに戻りません。キーワードがない場合、returnScala は関数の一部として評価された最後の式の結果を戻り値として扱います。この場合、常にrCountChange(money, coins tail, comb)無限再帰が発生します。

ここ:

def countChange(money: Int, coins: List[Int]): Int = {
  def rCountChange(money: Int, coins: List[Int], comb: Int): Int = {
    if (money >= coins(0)) rCountChange(money - coins(0), coins, comb) 
    else if (money == 0) comb + 1 //base case sequence found
    else if (coins.isEmpty) comb //base case sequence not found
    else rCountChange(money, coins tail, comb)
  }
  rCountChange(money, coins, 0)

}

または:

def countChange(money: Int, coins: List[Int]): Int = {
  def rCountChange(money: Int, coins: List[Int], comb: Int): Int = {
    if (money >= coins(0)) return rCountChange(money - coins(0), coins, comb) 
    if (money == 0) return comb + 1 //base case sequence found
    if (coins.isEmpty) return comb //base case sequence not found
    rCountChange(money, coins tail, comb)
  }
  rCountChange(money, coins, 0)

}
于 2013-04-04T16:46:35.967 に答える