prolog
prolog
4. Fibonacci Number
This program computes the Nth Fibonacci number using recursion. Two
base cases are defined: fibonacci(0, 0) and fibonacci(1, 1). For values
greater than 1, it recursively calculates the (N-1)th and (N-2)th
Fibonacci numbers and adds them. When queried like fibonacci(5, F).,
Prolog recursively calculates fibonacci(4) and fibonacci(3) until it
reaches the base cases, then combines the results. Although this
approach is not efficient due to overlapping subproblems (it
recalculates values repeatedly), it effectively demonstrates recursion.
In AI, Fibonacci-like problems can help visualize state transitions and
tree expansion. Prolog’s recursive structure naturally aligns with such
expansions. To optimize it, one could implement memoization or tail
recursion. Still, this naive version is an ideal beginner example for
understanding both the power and limitations of recursion in logic
programming and prepares learners for more complex recursive
structures used in AI tasks.
Prolog:-
fibonacci(0, 0).
fibonacci(1, 1).
fibonacci(N, F) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fibonacci(N1, F1),
fibonacci(N2, F2),
F is F1 + F2.
Query: fibonacci(6, F).
reverse_list([], []).
reverse_list([H|T], R) :- reverse_list(T, RevT), append(RevT, [H], R).
Query: palindrome([r,a,d,a,r]).