Definition (mathematical) function in Prolog

I know that Prolog (programming in logic) is all about returning true and false, and a function is something that returns something from lists, numbers, to logical values. Initially, Prolog doesn't seem to have a concept of functions, but instead relies on unification, but you can do things like:

?- X is log(42). X = 3.7376696182833684. 

So it seems that there are functions? Or is it really just some sort of syntactic sugar hiding part of the union?

And if it's really just syntactic sugar, then how would I go if I wanted to define a mathematical β€œfunction” like log2?

Of course, I can use unification:

 log2(X,Result) :- Result is log(X)/log(2). 

But I will say that I want to use the "syntactic style of the sugar function", so I can write:

 ?- X is log2(8). X = 3.0. 

How can I do this in Prolog?

+4
source share
2 answers

So this is just unification .. (thanks mbratch and checkmate for explanation)

This is how I solve my initial problem and thus makes my code more readable using self-imposed math functions:

 :- op(900, xfy, <-). R <- log2(Y) :- R is log(Y)/log(2), !. % the two predicates below solves the problem with using mathematical operators % together with self defined functions note that they should always be last % R <- X :- compound(X), X =..[OP, X2, X3], R2 <- X2, R3 <- X3, Expr =..[OP, R2, R3], R is Expr, !. R <- X :- R is X, !. 

then I can write:

 ?- X <- log2(8). X = 3.0. 

and, in addition, the last two predicates allow you to write compounds such as:

 ?- X <- 17*log2(8) - 2. X = 49.0. 

Please note that you are not allowed to mess with is / 2, and therefore I kind of cancel it, using my own <- operator instead

EDIT: added the syntactic sugar suggested by the mat, and added two predicates that fix problems when using the newly defined log2 in combination with other mathematical operators

+4
source

The prologue describes the relationship between entities. Since a mathematical function is a special kind of relationship (which associates input with a uniquely defined output), you can use Prolog to describe such functions. In your example, the predicate that implements this relation is called is/2 , and (is)/2 also defined as an infix operator in Prolog, so you can write:

?- X is log(42).

instead of the prefix form (which, of course, is still valid):

?- is(X, log(42)).

Note that is/2 performs arithmetic evaluations of expressions and unifies the first argument with the result. This differs from the unification of X word Prolog log(42) .

Note that is/2 not a true relation, because you cannot use it in another direction:

 ?- 0 is log(X). ERROR: is/2: Arguments are not sufficiently instantiated 

The solution to this is to use restrictions (for example, on real numbers called CLP (R)) that work in all directions. They are available as libraries or built-in modules in many modern Prolog systems.

+8
source

Source: https://habr.com/ru/post/1498730/


All Articles