Search code examples
prologfibonacciclpfd

What paradigm is this?


I have a question regarding different paradigms, I have this code example in Prolog

fib(0, 0).
fib(1, 1).
fib(V, VF) :­-
    B is V ­- 1, C is V ­- 2,
    fib(B, BF), fib(C, CF),
    VF is BF + CF.

can someone please tell me what paradigm this is and why it is that? Thank you in advance!


Solution

  • Let me first make the program easier to understand and also more general by using true arithmetic relations between integers instead of low-level arithmetic:

    :- use_module(library(clpfd)).
    
    fib(0, 0).
    fib(1, 1).
    fib(V, VF) :-
            V #> 1,
            B #= V - 1,
            C #= V - 2,
            VF #= BF + CF,
            fib(B, BF),
            fib(C, CF).
    

    Notice that since we are stating the solution in terms of true relations, we can also freely move the goals.

    The following queries now make it pretty clear why this is called logic programming:

    First, you can ask: Is there any solution?

    ?- fib(X, Y).
    X = Y, Y = 0 .
    

    Yes, there is!

    Then, you can ask for example: What is the 20-th Fibonacci number?

    ?- fib(20, Y).
    Y = 6765 .
    

    Further, you can ask: Which Fibonacci number(s) equal 233?

    ?- fib(X, 233).
    X = 13 .
    

    Further, you can ask: Is it true that the 10th Fibonacci number is 54?

    ?- fib(10, 54).
    false.
    

    No, it is not true.

    Thus, since we can ask logical questions and describe solutions by stating what holds in terms of logical relations, it is called logic programming.