Programming

9 thoughts
last posted July 1, 2015, 3:08 p.m.

5 later thoughts

0

This academic stuff is very arcane somehow. Let's go mainstream, but with a bit pattern-matching sugar:

fun fib(n: Int): Int {
    return when (n) {
        1, 2 -> 1
        else -> fib(n - 1) + fib(n - 2)
    }
}

fun main(args: Array<String>) {
    for (n in 1..10) {
        println("fib($n) = ${fib(n)}")
    }
}

Is recursion good? I don't know. Just make sure you use the iterative version in production code.

3 earlier thoughts