문제

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)
  }
도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top