An example of a nested function in Scala

Image for post
Image for post
Photo by Landon Martin on Unsplash
  @Test def testFind153SolFor3(): Unit = {
val expected = List(1, 3)
val actual = IntegerCalculator.find153Sol(3)
assertEquals(expected, actual)
}
@Test def testFind153SolForUnreachable(): Unit = {
val expected = List()
val actual = IntegerCalculator.find153Sol(15)
assertEquals(expected, actual)
}
@Test def testFind153SolFor8(): Unit = {
val expected = List(1, 3, 8)
val actual = IntegerCalculator.find153Sol(8)
assertEquals(expected, actual)
}
  def find153Sol(n: Int): List[Int] = {
def recur153(curr: Int, history: List[Int]): List[Int] = {
if (curr == n) {
history.drop(1) :+ n
} else if (curr > n) {
List()
} else {
val add5Branch = recur153(curr + 5, history :+ curr)
if (add5Branch.nonEmpty) {
add5Branch
} else recur153(curr * 3, history :+ curr)
}
}
recur153(1, List(1))
}

is a composer and photographer from Detroit, Michigan. He has been working on a Java program to display certain mathematical diagrams.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store