← All Examples Recursion
Fibonacci
A classic recursive Fibonacci function showing JAPL's expression-oriented design, where if/else blocks return values directly.
Source Code
fn fib(n: Int) -> Int {
if n <= 1 { n }
else { fib(n - 1) + fib(n - 2) }
}
fn main() {
println(show(fib(0)))
println(show(fib(1)))
println(show(fib(5)))
println(show(fib(10)))
} What This Demonstrates
- Expression-oriented if/else -- The
if/elseblock returns a value directly, noreturnkeyword needed. - Type annotations -- Function signatures declare parameter and return types with
name: Typesyntax. - Recursive functions -- Functions can call themselves naturally; the compiler verifies the types at every call site.
- Built-in
show-- Converts integers to strings for printing.
Line-by-Line Breakdown
fn fib(n: Int) -> Int- Declares a function named
fibthat takes anIntand returns anInt. The return type is explicit. if n <= 1 { n }- Base case: when
nis 0 or 1, the function returnsnitself. The block{ n }is an expression that evaluates ton. else { fib(n - 1) + fib(n - 2) }- Recursive case: computes the sum of the two preceding Fibonacci numbers. Both branches must return the same type (
Int). println(show(fib(10)))- Calls
fib(10), converts the result to a string withshow, and prints it. Result:55.
Try Modifying
- Add memoization by passing an accumulator: write
fib_acc(n, a, b)with tail recursion. - Change the base case to return a different starting sequence (e.g., Lucas numbers: 2, 1, 3, 4, 7...).
- Add a
fib_listfunction that builds a list of the first N Fibonacci numbers.