Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %% Backward chaining
- -module(backward).
- -export([start/0,mainLoop/0,solveGoal/2,solveRule/2,collect/3]).
- start() ->
- %% Initialize KB
- ets:new(rules, [bag, named_table]),
- ets:insert(rules, {g,[d,e,f,h,i,j],1.0}),
- ets:insert(rules, {g,[a,b,c],1.1}),
- ets:insert(rules, {a,[],0.1}),
- ets:insert(rules, {b,[],0.2}),
- ets:insert(rules, {c,[],0.3}),
- ets:insert(rules, {d,[],0.4}),
- ets:insert(rules, {e,[],0.5}),
- ets:insert(rules, {f,[],0.6}),
- ets:insert(rules, {h,[],0.7}),
- ets:insert(rules, {i,[],0.8}),
- ets:insert(rules, {j,[],0.9}),
- mainLoop().
- mainLoop() ->
- Query = io:read("Enter query: "),
- if
- Query == {ok, x} -> exit(normal);
- true -> ok
- end,
- Daddy = spawn(backward, solveGoal, [element(2, Query), self()]),
- receive
- {_, Truth} -> io:format("Answer is: ~w~n", [Truth]),
- exit(Daddy, ok)
- end,
- mainLoop().
- 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_link(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_link(backward, collect, [[], N, Caller]),
- %% For each subgoal in Rule
- %% Spawn a process to solve each subgoal
- lists:foreach(
- fun(Subgoal) -> spawn_link(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:sum(Truths)};
- true -> true
- end,
- receive
- {_, Truth} -> collect([Truth | Truths], N, Caller)
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement