Search code examples
scalacharacterstack-overflowstringbuilder

stringbuilder characters find


  def ff(c: Char): Boolean =  
  {
    while (cursor <= end)
    {
      if (buffer.charAt(cursor) == c)
      {
      return true
      }
      else
      {
      cursor += 1
      }
    }
    return false   
  }
  def ff(p: Char => Boolean): Boolean = 
  {
    ff(p)
  }

Idea of the function is to start at the cursor and find the next occurrence of a character defined by a variable called c taken as a parameter to the function, doing it this way results in a stackoverflow when tested with Junit could somebody explain where I'm going wrong?

Note(The cursor needs to stay at the position where the char is found)

I've also included the predicate version of the FF function where (p) is a predicate to search by I'm unsure which of these is causing the overflow.


Solution

  • ...could somebody explain where I'm going wrong?

    One thing you're doing wrong is using the Scala language to write C code. One of the goals/purposes/joys of learning a new language is that it can teach you a new way to approach problem solving. Taking the time to learn the idioms and best practices of a particular language is one way to get there.

    Some other things that aren't right:

    • import scala.io.StdIn - is unused
    • buffer.charAt(cursor) - This will throw if cursor== end, which the while condition allows.
    • def ff(p: Char => Boolean) - This does nothing but call itself. A guaranteed StackOverflow.

    See if this gets you closer to what you want.

    def ff(c: Char): Boolean = {
      val next = buffer.indexOf(c, cursor)
      cursor = if (next < 0) end else next
      cursor == next
    }
    def ff(p: Char => Boolean): Boolean =
      cursor != end && (p(buffer(cursor)) || {
        cursor += 1
        ff(p)
      })