Chapter 9. Indefinite Loops
You’ve seen in previous chapters how FP replaces for
and foreach
loops with LINQ functions like Select()
or Aggregate()
. That’s absolutely terrific, provided you are working with a fixed-length array, or an enumerable that will determine for itself when it’s time to finish iterating.
But what do you do when you aren’t at all sure how long you’ll want to iterate for? What if you’re iterating indefinitely until a condition is met?
I’ll start in this chapter by giving you a nonfunctional implementation of the ancient Indian board game Snakes and Ladders.1 Here are the rules for anyone who had a childhood tragically bereft of this board-game classic:
-
The board consists of 100 squares. The players start on square 1 and aim to reach square 100.
-
Each player takes a turn to roll a single die and to move their token forward the number of spaces indicated.
-
Landing on the bottom of a ladder means the playing piece should “climb” it to the top, advancing closer to square 100.
-
Landing on the head of a snake means the playing piece should “slide” down it to the end of the tail, moving farther away from square 100.
-
A player who rolls a 6 may take another turn.
-
The first player to reach square 100 wins.
This game has all sort of variations, but I’m going with these relatively simple, basic rules. Every edition of the game positions the snakes and ladders in all sorts of ways. The game we’ll be making, based on a version published in the early 20th century, ...
Get Functional Programming with C# now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.