Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %% Backward chaining
- -module(backward).
- -export([start/0,solveGoal/2,solveRule/2,collect/3,unify/2]).
- start() ->
- ets:new(rules, [bag, named_table]),
- ets:insert(rules, {g,[d,e,f,h,i,j],0.8}),
- ets:insert(rules, {g,[a,b,c],0.7}),
- ets:insert(rules, {a,[],0.9}),
- ets:insert(rules, {b,[],0.8}),
- ets:insert(rules, {c,[],0.9}),
- ets:insert(rules, {d,[],0.9}),
- ets:insert(rules, {e,[],0.6}),
- ets:insert(rules, {f,[],0.9}),
- ets:insert(rules, {h,[],0.9}),
- ets:insert(rules, {i,[],0.9}),
- ets:insert(rules, {j,[],0.9}),
- Query = io:read("Enter query: "),
- solveGoal(element(2, Query), self()),
- receive
- {_, Truth} -> io:format("Answer is: ~w~n", [Truth])
- end.
- solveGoal(Goal, Caller) ->
- %% Fetch rules...
- ApplicableRules = ets:match(rules,{Goal, '$1', '$2'}),
- lists:foreach(
- fun([RuleBody,Truth]) ->
- if
- %% If RHS is null
- RuleBody == [] -> Caller ! {Goal, Truth};
- %% If RHS contains subgoals
- true -> spawn(backward, solveRule, [RuleBody, self()])
- end end,
- ApplicableRules),
- receive
- %% Each message is of the form {goal,truth}
- %% Just accept the 1st answer
- {_, Truth} -> Caller ! {Goal, Truth}
- end.
- solveRule(RuleTail, Caller) ->
- N = length(RuleTail),
- Collector = spawn(backward, collect, [[], N, Caller]),
- %% For each subgoal in Rule
- %% Spawn a process to solve each subgoal
- lists:foreach(
- fun(Subgoal) -> spawn(backward, solveGoal, [Subgoal, Collector]) end,
- RuleTail).
- %% Accumulate results
- collect(Truths, N, Caller) ->
- %% If we have N messages send back the answer
- %% Answer = min of truth values, equivalent to fuzzy-logic AND
- if length(Truths) == N -> Caller ! {dont_care, lists:min(Truths)};
- true -> true
- end,
- receive
- {_, Truth} -> collect([Truth | Truths], N, Caller)
- end.
- %% Unify: just a stub
- unify(Goal,Rule) -> Goal == hd(Rule).
Advertisement
Add Comment
Please, Sign In to add comment