Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miguelemosreverte/35c78436887a6b4bdb4b025289935b3e to your computer and use it in GitHub Desktop.
Save miguelemosreverte/35c78436887a6b4bdb4b025289935b3e to your computer and use it in GitHub Desktop.
Recursion made simple
// 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