Created
October 20, 2013 19:23
-
-
Save shaunhess/7074056 to your computer and use it in GitHub Desktop.
Recursion in PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Google recursion and besides for the joke "Did you mean: recursion" you'll find a plethora of examples, definitions, and people showing you how clever they are. | |
| Put simply, recursion is broken down like this: | |
| Base case - simpliest possible solution | |
| Inductive step - break problem into a simplier version of the same problem with some other steps to execute. | |
| Ok clear as mud. So as always lets take a problem and break it down. | |
| A lot of examples show recursion using the Fibonacci sequence. However I always liked the "Blastoff!" example from How to Think Like a Computer Scientist. | |
| Alright lets define a function: | |
| function countdown { | |
| param( | |
| [int]$n | |
| ) | |
| if ($n -le 0) { | |
| Write-Host "Blastoff!" | |
| } else { | |
| $n | |
| countdown($n-1) | |
| } | |
| } | |
| Now lets source our function and run it: | |
| PS H:\Development\Powershell> . .\recursion.ps1 | |
| PS H:\Development\Powershell> countdown -n 10 | |
| 10 | |
| 9 | |
| 8 | |
| 7 | |
| 6 | |
| 5 | |
| 4 | |
| 3 | |
| 2 | |
| 1 | |
| Blastoff! | |
| See recursion isn't so bad after all. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment