Switch statements in Prolog - prolog

In Prolog predicates, I often write repetitive conditional statements like this one, but I wish they could be written more concisely:
output(Lang, Type, Output) :-
(Lang = javascript ->
Output = ["function", Type];
Lang = ruby ->
Output = ["def", Type];
Lang = java ->
Output = [Type]).
Would it be possible to replace this series of conditional statements with a more concise switch-statement?

In Prolog it is quite easy to define your own control structures, using meta-predicates (predicates that take goals or predicates as arguments).
For example, you could implement a switch construct like
switch(X, [
a : writeln(case1),
b : writeln(case2),
c : writeln(case3)
])
by defining
switch(X, [Val:Goal|Cases]) :-
( X=Val ->
call(Goal)
;
switch(X, Cases)
).
If necessary, this can then be made more efficient by compile-time transformation as supported by many Prolog systems (inline/2 in ECLiPSe, or goal expansion in several other systems).
And via operator declarations you can tweak the syntax to pretty much anything you like.

It seems that multiple clauses are made for this use case and also quite concise.
output(javascript, Type, ["javascript", Type]).
output(ruby, Type, ["def", Type]).
output(java, Type, [Type]).

slightly shorter:
output(Lang, Type, Output) :-
(Lang, Output) = (javascript, ["function", Type]) ;
(Lang, Output) = (ruby, ["def", Type]) ;
(Lang, Output) = (java, [Type]).
idiomatic:
output(Lang, Type, Output) :-
memberchk(Lang-Output, [
javascript - ["function", Type],
ruby - ["def", Type],
java - [Type]
]).

Related

"=>" symbol definition in Picat

What is the definition of the symbol "=>" in Picat and how do you read it ? Is it an implication ? I have trouble to understand it since there seems to be no informations about it in the manual nor in the book.
%example using "=>"
main =>
A = true,
B = true,
C = function(A,B),
predicate(A,B).
function(true,true) = R => R = true.
predicate(true,true) => true.
How would you describe the meaning of "=>" in the previous example ? Is it just something syntactically required, such as "{" after the declaration of a method in Java, or has a deeper meaning ?
Briefly, if you use => instead of :-, you are essentially writing a deterministic predicate. As we know that Prolog is a practical programming language and it is not necessary to keep all predicates pure. A lot of time, we actually write impure programs by cut and hope single sided unification. The => just provides a convenient mechanism to write such programs.
You can understand => by program transformation.
p(A1,A2,...An), C1, C2, ... => Body
is semantically equivalent to
p(V1,V2,...Vn) :-
Pattern = p(A1,A2,...An),
Args = p(V1,V2,...Vn),
subsumes_term(Pattern, Args),
Pattern = Args,
C1, C2, ...,
!,
Body.
More detail see https://swi-prolog.discourse.group/t/picat-style-matching

Evaluate term in Prolog and write it

Hi I am learning prolog (using swi-prolog 7 on Mac) but I cannot find enough docs/tutorials to explain how to print out a result of a term evaluation. I tried code below but it always prints out ERROR: prolog/test.pl:2: user:main: false for any arguments.
#!/usr/bin/env swipl
:- initialization(main, main).
fun1(A, B):- A < B.
fun2([A1 | A2]):- A3 is fun1(A1, A2), write(A3).
main(args) :- fun2(args).
How can I write result of fun1 to stdout in SWI-Prolog?
Perhaps this?
fun1(A,B,Value) :-
(
A < B
->
Value = true
;
Value = false
).
fun2(A1,A2) :-
fun1(A1, A2, Value ),
format('Result: ~w~n',[Value]).
Example run:
?- fun2(1,2).
Result: true
true.
In Prolog you have to think of the result of each line as being true or false and then possibly binding a value to a variable or something more complex as state.
The code in the question was returning that the predicate was true or false but not binding a value to a variable or altering state. By adding Value as an additional parameter and then binding a value in the predicate, the value in Value was able to be used for display.
EDIT
Question from OP in comment
I have never seen -> is it documented somewhere? Sorry if it is a noobie question.
No it is not a noobie question, and actually it was wise of you to just ask instead of festering on it.
See: Control Predicates
In particular ->/2 or (:Condition -> :Action) is often used with ;/2 and together they work like an if then else, e.g.
if then else syntax:
NB This is not Prolog syntax but a syntax common in many imperative programming languages.
if (<condition>) then
<when true>
else
<when false>
-> ; syntax:
This is Prolog syntax.
(
<condition>
->
<when true>
;
<when false>
)
EDIT
Question from OP in comment
When I run this code without the init block and main, so just in interactive mode, then it works. When I try to make a script out of it I get the same error ERROR: prolog/test.pl:2: user:main: false
First
main(args) :- fun2(args).
args is a value but needs to be a variable and in Prolog variables by default start with a capital letter.
main(Args) :- fun2(Args).
Next, Args as received in main/1 is a list, but fun2/2 expects two separate parameters. So by deconstructing Args into a list of two items with Args = [A1,A2] the items in the list can be used as individual items to be passed as parameters to fun2/2.
main(Args) :-
Args = [A1,A2],
fun2(A1,A2).
Example run from top level.
?- main([1,2]).
Result: true
true.
I leave it as an exercise to check if this works as needed from the command line.

Writing a predicate to add atoms

I have to write a predicate to do work like following:
?- cat(north,south,X).
X = northsouth
?- cat(alley,'91',Y).
X = alley91
?-cat(7,uthah,H).
Bad Input
H = H
Please Help..
atom_concat_redefined(A1, A2, A3) :-
( nonvar(A1) -> atom_chars(A1, Chs1) ; true ),
( nonvar(A2) -> atom_chars(A2, Chs2) ; true ),
( nonvar(A1), nonvar(A2) -> true ; atom_chars(A3, Chs3) ),
append(Chs1, Chs2, Chs3),
atom_chars(A1, Chs1),
atom_chars(A2, Chs2),
atom_chars(A3, Chs3).
This definition produces the same errors in a standard conforming implementation like SICStus or GNU - there should be no other differences, apart from performance. To compare the errors use the goal:
?- catch(atom_concat_redefined(A,B,abc+1), error(E,_), true).
E = type_error(atom,abc+1).
Note the underscore in error(E,_), which hides the implementation defined differences. Implementations provide additional information in this argument, in particular, they would reveal that atom_chars/2 or atom_concat/3 produced the error.
atom_codes/2 it's the ISO approved predicate to convert between an atom and a list of codes. When you have 2 lists corresponding to first two arguments, append/3 (alas, not ISO approved, but AFAIK available in every Prolog), will get the list corresponding to third argument, then, convert that list to atom...
Note that, while append/3 is a 'pure' Prolog predicate, and can work with any instantiation pattern, atom_codes/2 requires at least one of it's argument instantiated. Here is a SWI-Prolog implementation of cat/3, 'working' a bit more generally. I hope it will inspire you to read more about Prolog...
ac(X,Xs) :- when((ground(X);ground(Xs)), atom_codes(X,Xs)).
cat(X,Y,Z) :- maplist(ac, [X,Y,Z],[Xs,Ys,Zs]), append(Xs,Ys,Zs).
edit
as noted by #false I was wrong about append/3. Now I'll try to understand better what append/3 does... wow, a so simple predicate, so behaviour rich!

Parse To Prolog Variables Using DCG

I want to parse a logical expression using DCG in Prolog.
The logical terms are represented as lists e.g. ['x','&&','y'] for x ∧ y the result should be the parse tree and(X,Y) (were X and Y are unassigned Prolog variables).
I implemented it and everything works as expected but I have one problem:
I can't figure out how to parse the variable 'x' and 'y' to get real Prolog variables X and Y for the later assignment of truth values.
I tried the following rule variations:
v(X) --> [X].:
This doesn't work of course, it only returns and('x','y').
But can I maybe uniformly replace the logical variables in this term with Prolog variables? I know of the predicate term_to_atom (which is proposed as a solution for a similar problem) but I don't think it can be used here to achieve the desired result.
v(Y) --> [X], {nonvar(Y)}.:
This does return an unbound variable but of course a new one every time even if the logical variable ('x','y',...) was already in the term so
['X','&&','X'] gets evaluated to and(X,Y) which is not the desired result, either.
Is there any elegant or idiomatic solution to this problem?
Many thanks in advance!
EDIT:
The background to this question is that I'm trying to implement the DPLL-algorithm in Prolog. I thought it would by clever to directly parse the logical term to a Prolog-term to make easy use of the Prolog backtracking facility:
Input: some logical term, e.g T = [x,'&&',y]
Term after parsing: [G_123,'&&',G_456] (now featuring "real" Prolog variables)
Assign a value from { boolean(t), boolean(f) } to the first unbound variable in T.
simplify the term.
... repeat or backtrack until a assignment v is found so that v(T) = t or the search space is depleted.
I'm pretty new to Prolog and honestly couldn't figure out a better approach. I'm very interested in better alternatives! (So I'm kinda half-shure that this is what I want ;-) and thank you very much for your support so far ...)
You want to associate ground terms like x (no need to write 'x') with uninstantiated variables. Certainly that does not constitute a pure relation. So it is not that clear to me that you actually want this.
And where do you get the list [x, &&, x] in the first place? You probably have some kind of tokenizer. If possible, try to associate variable names to variables prior to the actual parsing. If you insist to perform that association during parsing you will have to thread a pair of variables throughout your entire grammar. That is, instead of a clean grammar like
power(P) --> factor(F), power_r(F, P).
you will now have to write
power(P, D0,D) --> factor(F, D0,D1), power_r(F, P, D1,D).
% ^^^^ ^^^^^ ^^^^
since you are introducing context into an otherwise context free grammar.
When parsing Prolog text, the same problem occurs. The association between a variable name and a concrete variable is already established during tokenizing. The actual parser does not have to deal with it.
There are essentially two ways to perform this during tokenization:
1mo collect all occurrences Name=Variable in a list and unify them later:
v(N-V, [N-V|D],D) --> [N], {maybesometest(N)}.
unify_nvs(NVs) :-
keysort(NVs, NVs2),
uniq(NVs2).
uniq([]).
uniq([NV|NVs]) :-
head_eq(NVs, NV).
uniq(NVs).
head_eq([], _).
head_eq([N-V|_],N-V).
head_eq([N1-_|_],N2-_) :-
dif(N1,N2).
2do use some explicit dictionary to merge them early on.
Somewhat related is this question.
Not sure if you really want to do what you asked. You might do it by keeping a list of variable associations so that you would know when to reuse a variable and when to use a fresh one.
This is an example of a greedy descent parser which would parse expressions with && and ||:
parse(Exp, Bindings, NBindings)-->
parseLeaf(LExp, Bindings, MBindings),
parse_cont(Exp, LExp, MBindings, NBindings).
parse_cont(Exp, LExp, Bindings, NBindings)-->
parse_op(Op, LExp, RExp),
{!},
parseLeaf(RExp, Bindings, MBindings),
parse_cont(Exp, Op, MBindings, NBindings).
parse_cont(Exp, Exp, Bindings, Bindings)-->[].
parse_op(and(LExp, RExp), LExp, RExp)--> ['&&'].
parse_op(or(LExp, RExp), LExp, RExp)--> ['||'].
parseLeaf(Y, Bindings, NBindings)-->
[X],
{
(member(bind(X, Var), Bindings)-> Y-NBindings=Var-Bindings ; Y-NBindings=Var-[bind(X, Var)|Bindings])
}.
It parses the expression and returns also the variable bindings.
Sample outputs:
?- phrase(parse(Exp, [], Bindings), ['x', '&&', 'y']).
Exp = and(_G683, _G696),
Bindings = [bind(y, _G696), bind(x, _G683)].
?- phrase(parse(Exp, [], Bindings), ['x', '&&', 'x']).
Exp = and(_G683, _G683),
Bindings = [bind(x, _G683)].
?- phrase(parse(Exp, [], Bindings), ['x', '&&', 'y', '&&', 'x', '||', 'z']).
Exp = or(and(and(_G839, _G852), _G839), _G879),
Bindings = [bind(z, _G879), bind(y, _G852), bind(x, _G839)].

Prolog build rules from atoms

I'm currently trying to to interpret user-entered strings via Prolog. I'm using code I've found on the internet, which converts a string into a list of atoms.
"Men are stupid." => [men,are,stupid,'.'] % Example
From this I would like to create a rule, which then can be used in the Prolog command-line.
% everyone is a keyword for a rule. If the list doesn't contain 'everyone'
% it's a fact.
% [men,are,stupid]
% should become ...
stupid(men).
% [everyone,who,is,stupid,is,tall]
% should become ...
tall(X) :- stupid(X).
% [everyone,who,is,not,tall,is,green]
% should become ...
green(X) :- not(tall(X)).
% Therefore, this query should return true/yes:
?- green(women).
true.
I don't need anything super fancy for this as my input will always follow a couple of rules and therefore just needs to be analyzed according to these rules.
I've been thinking about this for probably an hour now, but didn't come to anything even considerable, so I can't provide you with what I've tried so far. Can anyone push me into the right direction?
Consider using a DCG. For example:
list_clause(List, Clause) :-
phrase(clause_(Clause), List).
clause_(Fact) --> [X,are,Y], { Fact =.. [Y,X] }.
clause_(Head :- Body) --> [everyone,who,is,B,is,A],
{ Head =.. [A,X], Body =.. [B,X] }.
Examples:
?- list_clause([men,are,stupid], Clause).
Clause = stupid(men).
?- list_clause([everyone,who,is,stupid,is,tall], Clause).
Clause = tall(_G2763):-stupid(_G2763).
I leave the remaining example as an easy exercise.
You can use assertz/1 to assert such clauses dynamically:
?- List = <your list>, list_clause(List, Clause), assertz(Clause).
First of all, you could already during the tokenization step make terms instead of lists, and even directly assert rules into the database. Let's take the "men are stupid" example.
You want to write down something like:
?- assert_rule_from_sentence("Men are stupid.").
and end up with a rule of the form stupid(men).
assert_rule_from_sentence(Sentence) :-
phrase(sentence_to_database, Sentence).
sentence_to_database -->
subject(Subject), " ",
"are", " ",
object(Object), " ",
{ Rule =.. [Object, Subject],
assertz(Rule)
}.
(let's assume you know how to write the DCGs for subject and object)
This is it! Of course, your sentence_to_database//0 will need to have more clauses, or use helper clauses and predicates, but this is at least a start.
As #mat says, it is cleaner to first tokenize and then deal with the tokenized sentence. But then, it would go something like this:
tokenize_sentence(be(Subject, Object)) -->
subject(Subject), space,
be, !,
object(Object), end.
(now you also need to probably define what a space and an end of sentence is...)
be -->
"is".
be -->
"are".
assert_tokenized(be(Subject, Object)) :-
Fact =.. [Object, Subject],
assertz(Fact).
The main reason for doing it this way is that you know during the tokenization what sort of sentence you have: subject - verb - object, or subject - modifier - object - modifier etc, and you can use this information to write your assert_tokenized/1 in a more explicit way.
Definite Clause Grammars are Prolog's go-to tool for translating from strings (such as your English sentences) to Prolog terms (such as the Prolog clauses you want to generate), or the other way around. Here are two introductions I'd recommend:
http://www.learnprolognow.org/lpnpage.php?pagetype=html&pageid=lpn-htmlse29
http://www.pathwayslms.com/swipltuts/dcg/

Resources