Re: prolog like search
- To: mathgroup at smc.vnet.net
- Subject: [mg76667] Re: [mg76621] prolog like search
- From: Sseziwa Mukasa <mukasa at jeol.com>
- Date: Fri, 25 May 2007 06:42:54 -0400 (EDT)
- References: <200705241027.GAA22109@smc.vnet.net>
On May 24, 2007, at 6:27 AM, siewsk at bp.com wrote: > I would like to do prolog like searches in Mathematica > > entities={ william , henry , diana , charles } > Sonof(william,diana); > Sonof(william,charles); > Sonof(henry,diana); > Sonof(henry,charles); > > Married(A,B) := Sonof(S,A) && Sonof(S,B) && A != B; > > PrologSearch(Married,entities) > > returns { Married(diana,charles), Married(charles,diana) } > > Any idea how this could be implemented in Mathematica? It's been a while since I've looked at Prolog (and the second time I've heard it mentioned in the last 5 days) but if I recall correctly, Prolog does a depth first search with backtracking. The function you want would search the tree of values of sonof (it's easier in Mathematica not to capitalize the names of your expressions, or at least the initial letter) and return the values of married for which it's true. As I understand it Mathematica's pattern matcher does the depth first search, although I don't know how to emulate Prolog's cut, but you have to supply the implied sonof (x_,y_):=False for the other possible arguments of sonof. The other tricky part is preventing the evaluator from evaluating married[a_,b_] to a boolean, I'll choose to return the expressions as string then. The following works but requires much more work on the programmer's part than just doing it in Prolog: In[55]:= entities={ william , henry , diana , charles }; sonof[william,diana]:=True sonof[william,charles]:=True sonof[henry,diana]:=True sonof[henry,charles]:=True sonof[x_,y_]:=False married[a_,b_] := Or@@( sonof[#,a] && sonof[#,b] && ToString[a] !=ToString[ b]&/ @entities); prologSearch[pred_,entities_]:= Select[{pred[#[[1]],#[[2]]], ToString[pred]<>"["<>ToString[#[[1]]]<>","<>ToString[# [[2]]]<> "]"}&/@Tuples[entities,2],#[[1]]==True&][[All,2]] prologSearch[married,entities] Out[63]= {married[diana,charles],married[charles,diana]} There's probably a more clever and generalized way to do this using Mathematica's inherent pattern matching capabilities suing MatchQ but I haven't had enough coffee to figure it out yet. Regards, Ssezi
- References:
- prolog like search
- From: siewsk@bp.com
- prolog like search