Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recursion examples do not handle negative number input #48

Open
MariaLysik opened this issue Apr 16, 2018 · 0 comments
Open

Recursion examples do not handle negative number input #48

MariaLysik opened this issue Apr 16, 2018 · 0 comments

Comments

@MariaLysik
Copy link

For example, calling chessboard(-1) will lead to endless recursion and eventually stack overflow.

def chessboard(count: Int): Image = {
  val blackSquare = Image.rectangle(30, 30) fillColor Color.black
  val redSquare   = Image.rectangle(30, 30) fillColor Color.red
  val base = (redSquare beside blackSquare) above (blackSquare beside redSquare)
  count match {
    case 0 => base
    case n =>
      val unit = chessboard(n-1)
      (unit beside unit) above (unit beside unit)
  }
}

The solution could be just adding additional case on top:

case n if n<0 => Image.Empty

However, Dave suggested to turn it into a learning opportunity by adding:

  • Exercise: What would happen if we called chessboard() with a negative number? Why? How could we prevent this happening?
  • Solution: Explain that we fail to terminate. Explain underflow. Show your code using a guard clause to protect against this.

I like his approach better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant