lundi 25 janvier 2016

Why is Scala 'match' stuck in a forever loop

I'm trying to find out if numbers are descending within a list in Scala. When I run my test cases, the console prints an arbitrary list and never completes, making me think it's stuck in a forever loop.

The function isDescending must take a list as a parameter, and must return a boolean. We must use recursion and cannot use functions from the collections package.

Code:

  def isDescending(lst: List[Int]): Boolean ={
    isDescendingHelper(lst, 0, true)
  }

  def isDescendingHelper(lst: List[Int], prev: Int, begin: Boolean): Boolean = {
    lst match{
      case Nil =>  true
      case head :: tail => {
        if (begin){
          isDescendingHelper(lst, head, false)
        } else if (head <= prev){
          isDescendingHelper(lst, head, false)
        } else {
          false
        }
      }
    }
  }

Test Cases:

  test("isDescending test case"){
    assert(isDescending(List()))
    assert(isDescending(List(0, 0, 0)))
    assert(isDescending(List(3, 6, 8)))
    assert(isDescending(List(3, 6, 8 , 7)) == false)
    assert(isDescending(List(0)))
  }

Aucun commentaire:

Enregistrer un commentaire