Skip to content

Instantly share code, notes, and snippets.

@mhriess
Last active August 29, 2015 14:05
Show Gist options
  • Save mhriess/a252e2c111236f2c6395 to your computer and use it in GitHub Desktop.
Save mhriess/a252e2c111236f2c6395 to your computer and use it in GitHub Desktop.
simple recursion examples
def sumInts(a: Int, b: Int): Int =
if (a > b) 0 else a + sumInts(a + 1, b)
def countChange(money: Int, couns: List[Int]): Int = {
if (money == 0) 1
else if (money < 0) 0
else if (coins.isEmpty && money >= 1) 0
else {
countChange(money, coins.tail) + countChange(money - coins.head, coins)
}
}
def pascal(c: Int, r: Int): Int = {
if (c == 0 || c == r) 1
else pascal(c - 1, r - 1) + pascal(c, r - 1)
}
/**
* tail recursion
*/
def sum(f: Int => Int, a: Int, b: Int): Int = {
def loop(a: Int, acc: Int): Int = {
if (a > b) acc
else loop(a + 1, acc + f(a))
}
loop(a, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment