Last active
June 10, 2018 15:54
-
-
Save miguelemosreverte/35c78436887a6b4bdb4b025289935b3e to your computer and use it in GitHub Desktop.
Recursion made simple
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
// Recursion made simple | |
val dataset = List(5, 4, 3, 1, 8, 7) // dataset to use in below examples | |
// using inline bag | |
val firstResult = dataset.foldLeft((Int.MinValue, Int.MaxValue)) { case ((max, min), elem) => | |
if (elem > max) (elem, min) | |
else if (elem < min) (max, elem) | |
else (max, min) | |
} | |
println(firstResult) | |
// using outside bag for better mantainability | |
case class Bag(max: Int = Int.MinValue, min: Int = Int.MaxValue) | |
val secondResult = dataset.foldLeft(Bag()) { case (bag, elem) => | |
if (elem > bag.max) bag.copy(max = elem) | |
else if (elem < bag.min) bag.copy(min = elem) | |
else bag | |
} | |
println(secondResult) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment