00001
00002
00003 import java.io.BufferedReader;
00004 import java.io.IOException;
00005 import java.io.InputStreamReader;
00006 import java.util.regex.Matcher;
00007 import java.util.regex.Pattern;
00008
00009 import edu.tum.cs.prolog.PrologKnowledgeBase;
00010
00014 public class PrologShell {
00015
00016 public static void main(String[] args) {
00017 System.out.println("\n"+
00018 "The Simple yProlog Interactive Shell\n\n" +
00019 "usage:\n" +
00020 " tell: parent(eve, abel).\n" +
00021 " female(eve).\n" +
00022 " mother(X,Y) :- parent(X,Y), female(X).\n" +
00023 " ask: mother(eve, abel)\n" +
00024 " mother(eve, X)\n" +
00025 " consult: consult myfile.pl\n" +
00026 " exit: exit\n"
00027 );
00028
00029 PrologKnowledgeBase kb = new PrologKnowledgeBase();
00030 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
00031 String constant = "\\s*([a-z]\\w*|[0-9]+)\\s*";
00032 Pattern patGroundAtom = Pattern.compile(String.format("\\w+\\(%s(,%s)*\\)", constant, constant));
00033 for(;;) {
00034
00035 try {
00036
00037 System.out.print("\n> ");
00038 String input = br.readLine().trim();
00039
00040 if(input.equalsIgnoreCase("exit"))
00041 break;
00042
00043
00044 if(input.startsWith("consult")) {
00045 String filename = input.substring(7).trim();
00046 System.out.printf("consulting %s\n", filename);
00047 kb.consultFile(filename);
00048 }
00049 else if(input.endsWith("."))
00050 kb.tell(input);
00051 else {
00052 Matcher m = patGroundAtom.matcher(input);
00053 if(m.matches()) {
00054 boolean result = kb.ask(input);
00055 System.out.println(result ? "Yes" : "No");
00056 }
00057 else {
00058 for(String atom : kb.fetchAtoms(input)) {
00059 System.out.println(atom);
00060 }
00061 }
00062 }
00063 }
00064 catch (IOException e) {
00065 System.err.println(e.getMessage());
00066 }
00067 catch (java.lang.Exception e) {
00068 System.out.println(e.getMessage());
00069 }
00070 }
00071 }
00072 }