sobota, 24. januar 2009

Prolog Sweet Spot

The first time I came across Prolog I'd vomit. But first impressions are hardly objective.

For practice I wrote an evaluation function that takes an arbitrary statement of logical connectives and constants and print if it is true or not.

e.g.

?- eval(¬t → f,R).
R = t.


And the code

% this code comes without any kind of warranty!
% define operators
:- op(100,fy,¬).
:- op(200,yfx,∧).
:- op(300,yfx,∨).
:- op(400,yfx,→).
:- op(500,yfx,↔).

% define operator predicates
¬(f).
∧(t,t).
∨(f,f):-!,fail.
∨(_,_).
→(A,B):-eval(¬ A ∨ B,t).
↔(A,B):-eval((A → B) ∧ (B → A),t).

% define evaluation predicates
eval(t,t):-!.
eval(f,f):-!.

eval(Exp,Corr):-
Exp =.. [Op,Left,Right],
eval(Left,Corr1),
eval(Right,Corr2),
Top =.. [Op,Corr1,Corr2],
(call(Top) -> Corr = t; Corr = f),!.

eval(Exp,Corr):-
Exp =.. [Op,Left],
eval(Left,Corr1),
Top =.. [Op,Corr1],
(call(Top) -> Corr = t; Corr = f),!.


It is very easy to get this done in Prolog. In Java I don't think it will be that easy or fast. Just to think how to solve this and which library to use with Java will probably take more time than it took to write this Prolog code.

While I can't imagine writing database code in Prolog or something like that, but when it comes down to problems such as the mentioned Prolog wins hands down. Although negation is a bitch in Prolog.

Ni komentarjev: