Last active
October 12, 2023 01:38
-
-
Save dladukedev/4bf0c3d85b393fe91ddade11571f8668 to your computer and use it in GitHub Desktop.
Examples of Procedural vs Functional and Reactive styles of Programming
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
fun procedural() { | |
val numbers = (1..10).shuffled().toMutableList() | |
// Remove Even Numbers | |
var index = 0 | |
while(index < numbers.count()) { | |
if(numbers[index] % 2 == 0) { | |
numbers.removeAt(index) | |
} else { | |
index += 1 | |
} | |
} | |
// Double the values | |
for(i in numbers.indices) { | |
numbers[i] = numbers[i] * 2 | |
} | |
// Sort the Values Smallest to Largest | |
for (i in (1 until numbers.count())) { | |
val temp = numbers[i] | |
var swap = i | |
while(swap> 0 && numbers[swap- 1] > temp) { | |
numbers[swap] = numbers[swap- 1] | |
--swap | |
} | |
numbers[swap] = temp | |
} | |
// Print the Results | |
for(num in numbers) { | |
println(num) | |
} | |
} | |
fun functional() { | |
val numbers = (1..10).shuffled() | |
val oddNumbers = numbers.filter { it % 2 != 0 } | |
val doubledNumbers = oddNumbers.map { it * 2 } | |
val sortedNumbers = doubledNumbers.sorted() | |
sortedNumbers.forEach { println(it) } | |
} | |
fun reactive() { | |
val numbers = (1..10).shuffled().asSequence() | |
numbers.filter { it % 2 != 0 } | |
.map { it * 2 } | |
.sorted() | |
.onEach { println(it) } | |
.toList() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment