Domanda

Below is a simple 'repeat' method I am trying to write using tail recursion. The sole purpose of this function is to just repeat the giving string back to back 'n' amount of times.

I.e. repeat("Hello",3) = "HelloHelloHello"

But for whatever reason I am getting a 'java.lang.UnsupportedOperationException' and I am not sure why.

P.S. This is a homework assignment so if I could just be pointed in the right direction instead of a straight answer that would be cool!

  def repeat(s: String, n: Int): String = {
    def tailRepeat(str: String, x: Int): String = x match {
      case `n` => str
      case _ =>  val repeatString = s + str
      tailRepeat(repeatString, (x + 1))
    }
    tailRepeat(s, 0)
  }
È stato utile?

Soluzione

I think you are making this a little too complex. For one thing you don't really need pattern matching at all, you have a counting variable that tells you how many times to repeat your string, using that would simplify your code greatly. Also it is usually more straightforward to count down and not up:

def repeat(s: String, n: Int): String = {
    def tailRepeat(str: String, x: Int): String = {
        if(x == 0) str
        else       tailRepeat(str + s, x - 1)
    }
    tailRepeat(s, n - 1)
}

println( repeat("hello", 3) );
// hellohellohello
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top