Not fixed arity for a functor (Prolog) - prolog

In my Prolog program I have a predicate reg/1 which says if something is a regular expression. I'd like to make the program recognize sequences of regular expressions as a regular expression. So, if reg(a_1), reg(a_2), ..., reg(a_n) are all regular expressions, Prolog should answer yes/true to the query reg(a_1, a_2, ..., a_n).
But I don't know how to do it.
What I have done is the following:
reg([H|T]) :- reg(H), reg(T).
reg([X]) :- reg(X).
If, for example, reg(a), reg(b), reg(c) are all in the knowledge base, then Prolog answers yes/true to the query reg([a, b]) or reg([b, a, c]), but I can't ask it something like reg(a, b) or reg(b, a, c), i.e., I can't get rid of the square brackets.

It is very uncommon in Prolog to use the same structure with varying arities. To show you one such place where they could have been used but are not, consider directives as they are used to declare a predicate dynamic, multifile, or discontiguous. Say, I want to declare a/2 and b/5 dynamic. The following options are possible in ISO-Prolog:
:- dynamic(a/2).
:- dynamic(b/5).
:- dynamic([a/2,b/5]). % using a list
:- dynamic((a/2,b/5)). % using an and-sequence
Additionally, many Prolog systems have declared dynamic/1 a prefix operator (as an implementation specific extension) such that you can write:
:- dynamic a/2.
:- dynamic b/5.
:- dynamic [a/2,b/5].
:- dynamic a/2, b/5.
However, there is no
:- dynamic(a/2,b/5). % does not work
which would correspond to your idea.
If you really want to use that representation, you will need (=..)/2 for that. I'd say this is a source of many potential bugs.
The only case that comes to mind where a structure with "variable" arity is commonly used are compact representations of sets of variables, as they are used in the implementation of setof/3. Instead of using a list of variables Vs the structure V is used.
term_varvect(T, V) :-
term_variables(T, Vs),
V =.. ['.'|Vs]. % some use v instead of '.'
In systems with a limited max_arity you have to handle the overflow case:
term_varvect(T, V) :-
term_variables(T, Vs),
catch( V =.. ['.'|Vs],
error(representation_error(max_arity), _),
Vs = V).

Related

Creating Metavariables in Prolog

I am working with implementing a unification algorithm for a term rewriting system in Prolog. To fully implement this, I need a predicate substituting out a given subterm for another term. Unfortunately, the way that Prolog instantiates fresh variables prevents the system from successfully be able to achieve this. I have some built in operators, star and divi (really just representing the * and / symbols, but in prefix form). My substitute predicate is made up of the following predicates:
replace(A,B, [], []).
replace(A,B, [H|T], [B|T2]) :- (H==A)->replace(A, B, T, T2).
replace(A,B, [H|T], [H|T2]) :- (H\==A)->replace(A, B, T, T2).
replace_lst([], [H|T], [H2|T2]).
replace_lst([H1|T1], [H|T], [H2|T2]) :-
arg(1,H1,X),
arg(2,H1,Y),
replace(X,Y,[H|T],[H2|T2]),
replace_lst(T1,[H|T],[H2|T2]).
substitute([H|T],A,X):-
A=..List,
replace_lst([H|T],List,C),
X=..C.
Where this runs into trouble is that, for instance, the terms star(X,X) and star(Y,Y), are, by the logic of my rewrite system, structurally equivalent and require no such substitution. However, comparing these two terms using the unifiable predicate will lead Prolog to attempting unification for the two, and the resulting term is no longer equivalent in structure to the original star(X,X) structure. Therefore, I attempted to check for term equality through their structure, but this leads to another can of worms in which, for instance, my rewrite system contains the rewrite rule:
star(X,X)==>X.
However,attempting to substitute based on the variant equality =#= operator leads to the issue of Prolog seeing two differently instantiated terms with the same structure as the same term. Therefore, defining a variant-based subtitution predicate like so:
variant_replace(A,B, [], []).
variant_replace(A,B, [H|T], [B|T2]) :- (H=#=A)->variant_replace(A, B, T, T2).
variant_replace(A,B, [H|T], [H|T2]) :- (H\=#=A)->variant_replace(A, B, T, T2).
variant_replace_lst([], [H|T], [H2|T2]).
variant_replace_lst([H1|T1], [H|T], [H2|T2]) :-
arg(1,H1,X),
arg(2,H1,Y),
variant_replace(X,Y,[H|T],[H2|T2]),
variant_replace_lst(T1,[H|T],[H2|T2]).
variant_substitute([H|T],A,X):-
A=..List,
variant_replace_lst([H|T],List,C),
X=..C.
Leads to an issue where if I have some term:
star((star(X,Y),star(A,B))
and I want to substitute the star(X,Y) subterm with the following predicate:
?- variant_substitute([star(X,Y)=hole],star(star(X,Y),star(A,B)),D).
D = star(hole, hole) .
We can see Prolog, by the logic of the variant substitution predicate, will simply check for terms of a given structure, disregarding the actual variable instantiation. Therefore, I need a way to declare variables. What I desire is to have a system that is able to use metavariables declared in such a way each given term has up to N unique variables, ranging in value from V(0) to V(N-1). Ideally, such a system of metavariables would look like so:
substitute([star(v(0),v(1))=hole],star(star(v(0),v(1)),star(v(2),v(3))),D).
D = star(hole, star(v(2), v(3)))
I need Prolog to see terms denoted with v(#) as variables since I will need to use the unifiable predicate down the road to compare them to the original declaration of my rewrite rules, which is declared like so :
star(X,X) ==> X.
divi(X,X) ==> X.
divi(star(X,Y),Y) ==> X.
star(divi(X,Y),Y) ==> X.
star(X, star(Y,Z)) ==> star(star(divi(X,Z),Y),Z).
divi(X, star(Y,Z)) ==> star(divi(divi(X,Z),Y),Z).
star(X, divi(Y,Z)) ==> divi(star(star(X,Z),Y),Z).
divi(X, divi(Y,Z)) ==> divi(divi(star(X,Z),Y),Z).
What would be the best way to implement this format of metavariable in Prolog?

How do I determine if a prolog `compund term` has a particular `atom` inside?

I want a predicate to tell whether a particular atom (say x) appears inside a compound term, however deeply nested.
I tried to read about predicates given at https://www.swi-prolog.org/pldoc/man?section=manipterm. I think it will involve walking down the compound term using functor/3 and ../2 recusively. Is there a simpler approach, or some library that does this?
Carlo's elegant answer works on SWI-Prolog but is not portable as the ISO Prolog standard specification for the arg/3 predicate (which most Prolog systems implement) requires its first argument to be bound to an integer, preventing using it as a backtracable generator of compound term arguments. A more portable alternative would be:
haystack_needle(H, N) :-
H == N.
haystack_needle(H, N) :-
functor(H, _, A),
between(1, A, I),
arg(I, H, A),
haystack_needle(A, N).
The between/3 predicate is not specified in the ISO Prolog standard but it's a de facto standard predicate usually provided as either a built-in predicate or a library predicate.
Ignoring cyclic terms, I would use ==/2,compound/1 and arg/3
haystack_needle(H,N) :- H==N.
haystack_needle(H,N) :- compound(H),arg(_,H,A),haystack_needle(A,N).
haystack_needle/2 will succeed multiple times, then will allow for counting occurrences:
?- aggregate(count, haystack_needle(t(a,x,b,[x,x,x]),x), C).
C = 4.
Note, the needle does not need to be an atom...
You can use once/1 to tell if needle appears in haystack:
?- once(haystack_needle(t(a,x,b,[x,x,x]),x)).
true.
?- once(haystack_needle(t(a,x,b,[x,x,x]),z)).
false.
As noted by Paulo, arg/3 could not act appropriately in ISO compliant Prologs.
A portable alternative (with arguments swapped without other purpose than avoiding confusion) could be
needle_haystack(N,H) :- N==H.
needle_haystack(N,H) :- H=..[_|As],member(A,As),needle_haystack(N,A).
Of course, if member/2 is available :)

How to call a predicate from another predicate in Prolog?

So I just started Prolog and I was wondering two things:
1) Is there built in functions (or are they all called predicates?) for simple things like max of 2 numbers, or sine of a number, etc... If so, how do I access them?
2) How can I call a predicate from another one? I wrote two predicates called car and cdr. car returns the head of a list and cdr returns the list without the head. But now I want to call car on the cdr. Here are some examples for clarification:
car([3,4,5,5], H). would return H = 3
cdr([3,4,5,5],L). would return L = [4,5,5]
and what I am asking is how can I do this:
car(cdr[3,4,5,5]))
??
As others have pointed out, the predicates in Prolog are called that for a reason: they really aren't functions. Many newcomers to Prolog start out by trying to map the functionality they know in other languages over to Prolog and it generally fails. Prolog is a very different programming tool than most other languages. So it's a bit like using a variety of hammers for a long time, then having someone hand you a wrench, and you wonder why it doesn't make a good hammer.
In Prolog, predicates are a means of declaring relations between entities. If you say foo(a, b) it means there's a relationship between a and b called foo. You've probably seen the examples: knows(joe, jim). and knows(jim, sally). And you can define a relation, like:
remotely_acquainted(X, Y) :- knows(X, Z), knows(Z, Y), \+ knows(X, Y).
Or something like that.
A predicate does not return a value. It either succeeds or it fails. If you have a sequence of predicates separated by commas (an "and" relationship) and Prolog encounters a predicate that fails, it backs up (backtracks) to the nearest prior predicate which it can make succeed again with different instantiation of its arguments and moves forward again.
Just to add a little to the confusion, there are some predicates in Prolog designed specifically for the evaluation of arithmetic expressions. These act like functions, but they are special case. For example:
X is Y / gcd(Z, 4).
Here, gcd of Z and 4 is computed an its value returned, and then Y is divided by that value and the result is instantiated into X. There are a variety of other functions as well, such as max/2, sin/1, etc. You can look them up in the documentation.
Arithmetic comparative operators function this way as well (using =:=/2, >/2, </2, etc with numeric expressions). So if you say:
X < Y + Z
The Prolog will consider numerical evaluation of these arguments and then compare them.
So having said all that, Prolog does allow embedding of term structures. You could have something like:
car(cdr([1,2,3]))
as a term. Prolog will not interpret it. Interpretation is left up to the programmer. I could then create a predicate which defines an evaluation of such terms:
car([H|_], H).
cdr([_|T], T).
proc_list(car(X), Result) :-
proc_list(X, R1),
car(R1, Result), !.
proc_list(cdr(X), Result) :-
proc_list(X, R1),
cdr(R1, Result), !.
proc_list(X, X).
The cut in the above clauses prevents backtracking to proc_list(X, X) when I don't want it.
Then:
| ?- proc_list(car(cdr([1,2,3])), R).
R = 2
yes
| ?- proc_list(car(cdr(cdr([1,2,3]))), R).
R = 3
yes
| ?-
Note this is a simple case and I may not have captured all of the subtleties of doing a proper sequence of car and cdr. It can also be made more general using =.. and call, etc, instead of discrete terms car and cdr in the parameters. For example, a slightly more general proc_list might be:
proc_list(Term, Result) :-
Term =.. [Proc, X], % Assumes terms have just one argument
member(Proc, [car, cdr]), % True only on recognized terms
proc_list(X, R1), % Recursively process embedded term
ProcCall =.. [Proc, R1, Result], % Construct a calling term with Result
call(ProcCall), !.
proc_list(X, X).
This technique of processing a term does step away from relational behavior which Prolog is best at, and leans into functional behavior, but with an understand of how Prolog works.
Prolog has a really different attitude to computing...
You don't define functions, but relations among arguments. The most similar and well known language I'm aware of is SQL. Think of predicates as tables (or stored procedures, when some computation not predefined by database engine is required).
car([H|_],H).
cdr([_|T],T).
car_of_cdr(L, Car) :- cdr(L, Cdr), car(Cdr, Car).
but since lists' syntax is a core part of the language, a better definition could be
car_of_cdr([_,X|_], X).
Anyway, I think you should spend some time on some Prolog tutorial. SO info page has much more information...
:- use_module(support).
This means the module will use predicates written in other modules.
<module_name>:<predicate_name>(<atoms / Variables>).
This way you can call a predicate in another module.

How do I define a binary operation on a set of numbers in prolog?

How do I define a binary operation on a list in prolog and then check its properties such as closure , associative, transitive , identity etc. ? I am new to prolog.. I don't know whether it is the place to ask but I tried and I didn't come across anything somewhere.
In Prolog you define predicates, i.e. relations among a symbol (called functor) and its arguments.
A predicate doesn't have a 'return value', just a 'truth value', depending of whether it can be evaluated WRT its arguments. Then your question it's not easy to answer.
Associativity, transitivity, identity, are of little help when it come down to speaking about predicates. The first and most common property we wish to evaluate is termination, because Prolog control flow it's a bit unusual and can easily lead to infinite recursion.
Anyway, the simpler binary relation on a list is member/2, that holds when its first argument it's an element of the second argument (the list).
member(X, [X|_]).
member(X, [_|T]) :- member(X,T).
I can't see any benefit in assessing that it's not associative, neither transitive (its arguments are of different types !).
Common operations like intersection, union, etc typically needs 3 arguments, where the last is the result of the operation performed between 2 lists.
Identity in Prolog (that is an implementation of first order logic) deserves a special role. Indeed, the usual programming symbol = used to assess identity, really performs a (potentially) complex operation, called unification. You can see from the (succint) documentation page that it's 'just' a matching between arbitrary terms.
You could do something like this:
% Define sets I want to try
set7([0,1,2,3,4,5,6]).
% Define operations
% Sum modulo 7
sum7(X, Y, R) :-
R is (X+Y) mod 7.
% Normal sum
nsum(X, Y, R) :-
R is X + Y.
% A given set is closed if there is not a single case which
% indicates that it is not closed
closed(S, Operator) :-
\+ n_closed(S, Operator, _), !.
% This predicate will succeed if it finds one pair of elements
% from S which, when operated upon, will give a result R which
% is outside of the set
n_closed(S, Operator, R) :-
member(X, S),
member(Y, S),
Operation =.. [Operator, X, Y, R],
Operation,
\+ member(R, S).
When you execute it, you get these results:
| ?- set7(S), closed(S, sum7).
(1 ms) yes
| ?- set7(S), closed(S, nsum).
no
I'm not convinced my closure check is optimal, but it gives some ideas for how to play with it.

binary predicate to square list and sublists in Prolog

I am new to prolog and was trying to create a binary predicate which will give
a list in which all numbers are squared, including those in sublists.
e.g.
?-dcountSublists([a,[[3]],b,4,c(5),4],C).
C=[a,[[9]],b,c(5),16]
Can anyone guide me how i can do this.
Thank You. Answer with a snippet is appreciated
This is easily achieved using recursion in Prolog. Remember that everything in Prolog is either a variable, or a term (atoms are just 0-arity terms), so a term like the following:
[a,[[3]],b,4,c(5),4]
...is easily deconstructed (also note that the list syntax [..] is sugar for the binary predicate ./2). Prolog offers a range of predicates to test for particular types of terms as well, such as numbers, strings, or compound terms (such as compound/1).
To build the predicate you're after, I recommend writing it using several predicates like this:
dcountSublists(In, Out) :-
% analyze type of In
% based on type, either:
% 1. split term into subterms for recursive processing
% 2. term cannot be split; either replace it, or pass it through
Here's an example to get you started which does the hard bit. The following recognizes compound terms and breaks them apart with the term de/constructor =../2:
dcountSublists(In, Out) :-
% test if In has type compound term
compound(In),
% cut to exclude backtracking to other cases below this predicate
!,
% deconstruct In into functor and an argument list
In =.. [Func|Args],
% apply dcountSublists/2 to every argument, building new args
maplist(dcountSublists, Args, NewArgs),
% re-construct In using the new arguments
Out =.. [Func|NewArgs].
dcountSublists(In, Out) :-
% test if In has type atom
atom(In), !,
% pass it through
Out = In.
Testing:
?- dcountSublists([a,[[e]],b,a,c(s),a], L).
L = [a, [[e]], b, a, c(s), a].
Note that this fails if the input term has numbers, because it doesn't have a predicate to recognize and deal with them. I'll leave this up to you.
Good luck!
SWI-Prolog has the predicate maplist/[2-5] which allows you to map a predicate over some lists.
Using that, you only have to make a predicate that will square a number or the numbers in a list and leave everything else the same. The predicates number/1, is_list/1 are true if their argument is a number or a list.
Therefore:
square(N,NN):-
integer(N),
NN is N*N.
square(L,LL):-
is_list(L),
dcountSublists(square,L,LL).
square(Other,Other):-
\+ number(Other),
\+ is_list(Other).
dcountSublists(L,LSquared):-
maplist(square,L,LSquared).
with the negation in the final predicate we avoid multiple (wrong) solutions:
for example dcountSublists([2],X) would return X=[4] and X=[2] otherwise.
This could be avoided if we used an if-then-else structure for square or once/1 to call square/2.
If this is homework maybe you should not use maplist since (probably) the aim of the exercise is to learn how to build a recursive function; in any case, I would suggest to try and write an equivalent predicate without maplist.

Resources