Difference between logic programming and functional programming

前端 未结 8 896
萌比男神i
萌比男神i 2021-01-29 22:56

I have been reading many articles trying to understand the difference between functional and logic programming, but the only deduction I have been able to make so far is that lo

8条回答
  •  北海茫月
    2021-01-29 23:37

    In a nutshell:

    In functional programming, your program is a set of function definitions. The return value for each function is evaluated as a mathematical expression, possibly making use of passed arguments and other defined functions. For example, you can define a factorial function, which returns a factorial of a given number:

    factorial 0 = 1                       // a factorial of 0 is 1
    factorial n = n * factorial (n - 1)   // a factorial of n is n times factorial of n - 1 
    

    In logic programming, your program is a set of predicates. Predicates are usually defined as sets of clauses, where each clause can be defined using mathematical expressions, other defined predicates, and propositional calculus. For example, you can define a 'factorial' predicate, which holds whenever second argument is a factorial of first:

    factorial(0, 1).               // it is true that a factorial of 0 is 1
    factorial(X, Y) :-             // it is true that a factorial of X is Y, when all following are true:
        X1 is X - 1,                   // there is a X1, equal to X - 1,
        factorial(X1, Z),              // and it is true that factorial of X1 is Z, 
        Y is Z * X.                    // and Y is Z * X
    

    Both styles allow using mathematical expressions in the programs.

提交回复
热议问题