Slide 6
Slide 6 text
Functional eye for the
imperative guy
fun factorial(n: Long): Long {
var result = 1L
for (it in 1..n) {
result *= it
}
return result
}
fun functionalFactorial(n: Long): Long {
fun go(n: Long, acc: Long): Long {
return if (n <= 0) {
acc
} else {
go(n - 1, n * acc)
}
}
return go(n, 1)
}
fun tailrecFactorial(n: Long): Long {
tailrec fun go(n: Long, acc: Long): Long {
return if (n <= 0) {
acc
} else {
go(n - 1, n * acc)
}
}
return go(n, 1)
}
factorial(20)*
0μs
0,025μs
0,05μs
0,075μs
0,1μs
factorial functional tailrec
Error Value
0,064
0,092
0,078
0,001
0,003
0,002
0,002 0,003 0,001
*Calculated with JMH, SampleTime mode