Created
August 27, 2019 11:20
-
-
Save hgbrown/af5468d26b2fa7a392fe4016ae7c0c5b to your computer and use it in GitHub Desktop.
Demonstrates the importance of limiting the scope of variables to the smallest possible scope.
This file contains 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
package dev.hbrown | |
/** | |
* Demonstrates the importance of limiting the scope of a variable using the Sieve of Eratosthenes to find prime numbers | |
* using a sequence builder. The algorithm is conceptually very easy: | |
* | |
* 1. take a list of numbers starting at 2. | |
* 2. remove the first number, it is prime. | |
* 3. from the rest of the numbers, remove the first number as well as all the numbers divisible by this prime number. | |
* | |
* In [limitedScope] we limit the scope of the `prime` variable to the loop where it is needed. | |
* In [scopeNotLimited] we attempt to 'optimise' the need to create the variable in every loop away by moving the | |
* variable outside of the loop. | |
* | |
*/ | |
class LimitingScopeOfVariables { | |
fun limitedScope() { | |
val primes: Sequence<Int> = sequence { | |
var numbers = generateSequence(2) { it + 1 } | |
while (true) { | |
val prime = numbers.first() | |
yield(prime) | |
numbers = numbers.drop(1).filter { it % prime != 0 } | |
} | |
} | |
println("limitedScope: ${primes.take(10).toList()}") | |
} | |
fun scopeNotLimited() { | |
val primes: Sequence<Int> = sequence { | |
var numbers = generateSequence(2) { it + 1 } | |
var prime: Int | |
while (true) { | |
prime = numbers.first() | |
yield(prime) | |
numbers = numbers.drop(1).filter { it % prime != 0 } | |
} | |
} | |
println("scopeNotLimited: ${primes.take(10).toList()}") | |
} | |
companion object { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val eg = LimitingScopeOfVariables() | |
eg.limitedScope() //[2, 3, 5, 7, 11, 13, 17, 19, 23, 29] | |
eg.scopeNotLimited() //[2, 3, 5, 6, 7, 8, 9, 10, 11, 12] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment