← 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

Line-by-Line Breakdown

fn fib(n: Int) -> Int
Declares a function named fib that takes an Int and returns an Int. The return type is explicit.
if n <= 1 { n }
Base case: when n is 0 or 1, the function returns n itself. The block { n } is an expression that evaluates to n.
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 with show, and prints it. Result: 55.

Try Modifying