Cybernetic1

Untitled

Apr 16th, 2012
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.82 KB | None | 0 0
  1. %% Backward chaining
  2.  
  3. -module(backward).
  4. -export([start/0,solveGoal/2,solveRule/2,collect/3,unify/2]).
  5.  
  6. start() ->
  7.     ets:new(rules, [bag, named_table]),
  8.     ets:insert(rules, {g,[d,e,f,h,i,j],0.8}),
  9.     ets:insert(rules, {g,[a,b,c],0.7}),
  10.     ets:insert(rules, {a,[],0.9}),
  11.     ets:insert(rules, {b,[],0.8}),
  12.     ets:insert(rules, {c,[],0.9}),
  13.     ets:insert(rules, {d,[],0.9}),
  14.     ets:insert(rules, {e,[],0.6}),
  15.     ets:insert(rules, {f,[],0.9}),
  16.     ets:insert(rules, {h,[],0.9}),
  17.     ets:insert(rules, {i,[],0.9}),
  18.     ets:insert(rules, {j,[],0.9}),
  19.     Query = io:read("Enter query: "),
  20.     solveGoal(element(2, Query), self()),
  21.     receive
  22.         {_, Truth} -> io:format("Answer is: ~w~n", [Truth])
  23.     end.
  24.  
  25. solveGoal(Goal, Caller) ->
  26.     %% Fetch rules...
  27.     ApplicableRules = ets:match(rules,{Goal, '$1', '$2'}),
  28.     lists:foreach(
  29.         fun([RuleBody,Truth]) ->
  30.         if
  31.             %% If RHS is null
  32.             RuleBody == [] -> Caller ! {Goal, Truth};
  33.             %% If RHS contains subgoals
  34.             true -> spawn(backward, solveRule, [RuleBody, self()])
  35.         end end,
  36.         ApplicableRules),
  37.     receive
  38.         %% Each message is of the form {goal,truth}
  39.         %% Just accept the 1st answer
  40.         {_, Truth} -> Caller ! {Goal, Truth}
  41.     end.
  42.  
  43. solveRule(RuleTail, Caller) ->
  44.     N = length(RuleTail),
  45.     Collector = spawn(backward, collect, [[], N, Caller]),
  46.     %% For each subgoal in Rule
  47.     %% Spawn a process to solve each subgoal
  48.     lists:foreach(
  49.         fun(Subgoal) -> spawn(backward, solveGoal, [Subgoal, Collector]) end,
  50.         RuleTail).
  51.  
  52. %% Accumulate results
  53. collect(Truths, N, Caller) ->
  54.     %% If we have N messages send back the answer
  55.     %% Answer = min of truth values, equivalent to fuzzy-logic AND
  56.     if length(Truths) == N -> Caller ! {dont_care, lists:min(Truths)};
  57.        true -> true
  58.     end,
  59.     receive
  60.         {_, Truth} -> collect([Truth | Truths], N, Caller)
  61.     end.
  62.  
  63. %% Unify: just a stub
  64. unify(Goal,Rule) -> Goal == hd(Rule).
Advertisement
Add Comment
Please, Sign In to add comment