⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 prolog.java

📁 人工智能代码JAVA程序,包括神经网络,遗传算法
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/**
 * CKI Prolog is an prolog interpreter
 * Sieuwert van Otterloo
 * http://www.students.cs.uu.nl/~smotterl/prolog
 * smotterl@cs.uu.nl
 * 1999
 */

/**
 * Note: from on the web site
 * http://www.students.cs.uu.nl/~smotterl/prolog
 * is a message:
 * "The sourcecode of CKI prolog is free. This means
 * that it can be modified by anyone."
 *
 * In addition, I received specific permission from
 * Sieuwert van Otterloo use this code for an example
 * for my Java AI book.  -Mark Watson
 */

/**
 * Note #2: Sieuwert's original code was a nice
 * Java applet with a user interface for Prolog.
 * I removed the user interface code and added an
 * API (top level Prolog class) for using the
 * Prolog engine in Java applications. -Mark Watson
 */

import java.util.*;
import java.io.*;

/**********************************************************
 * PROLOG
 **********************************************************/

public class Prolog {
    program prog;
    solver sv;
    static private boolean once = true;

    public Prolog() {
        prologop.makeops();
        if (once) {
            System.out.println("CKI Prolog Engine. By Sieuwert van Otterloo.\n");
            once = false;
        }
        prog=new program();
        sv=new solver(prog);
        prog.setsolver(sv);
    }
    public void assert(String s) {
        term inp=(new prologtokenizer(s)).gettermdot(null);
        if (sv.assert(inp) == false) {
            System.out.println("Error asserting: " + s);
        }
    }
    public Vector solve(String s) {
        term inp=(new prologtokenizer(s)).gettermdot(null);
        sv.query(inp);
        return sv.getAnswers();
    }
    public boolean consultFile(String filename) {
	return consultFile(filename, false);
    }
    public boolean consultFile(String filename, boolean quiet) {
	try {
	    FileReader fr = new FileReader(filename);
	    BufferedReader br = new BufferedReader(fr);
	    int count = 0;
	    while (true) {
		String line = br.readLine();
		if (line == null) break;
		if (quiet == false) System.out.println(line);
		line = line.trim();
		if (line.startsWith("%") || line.length() < 1) continue;
		if (line.endsWith(".")) {
		    assert(line);
		} else {
		    while (line.endsWith(".") == false) {
			String s2 = br.readLine();
			if (quiet == false) System.out.println(s2);
			line = line + " " + s2;
		    }
		    assert(line);
		}
	    }
	    br.close();
	    return true; // OK
	} catch (Exception e) {
	    System.out.println("consultFile error: " + e);
	    e.printStackTrace();
	}
	return false;
    }

    static public void main(String [] args) {
	if (args.length == 0) {
	    /**
	     * Simple example howing how to use embedded Prolog
	     * in your Java programs:
	     */
	    Prolog p = new Prolog();
	    p.assert("father(ken,mark).");
	    p.assert("father(ken,ron).");
	    p.assert("father(ron,anthony).");
	    p.assert("grandfather(X,Z):-father(X,Y),father(Y,Z).");
	    Vector v = p.solve("grandfather(X,Y).");
	    System.out.println("test results:");
	    //      Vector v = p.solve("permutation([1,2,3],X).");
	    for (int i=0; i<v.size(); i++) {
		System.out.println();
		Hashtable the_answers = (Hashtable)v.elementAt(i);
		Enumeration enum = the_answers.keys();
		while (enum.hasMoreElements()) {
		    String var = (String)enum.nextElement();
		    String val = (String)the_answers.get(var);
		    System.out.println(" var: " + var + "   val: " + val);
		}
	    }
	} else if (args.length > 1) {
	    /**
	     * Two arguments: a prolog file and a query
	     */
	    try {
		Prolog p = new Prolog();
		p.consultFile(args[0]);
		Vector v = p.solve(args[1]);
		for (int i=0; i<v.size(); i++) {
		    System.out.println("\nNext answer:");
		    Hashtable the_answers = (Hashtable)v.elementAt(i);
		    Enumeration enum = the_answers.keys();
		    while (enum.hasMoreElements()) {
			String var = (String)enum.nextElement();
			String val = (String)the_answers.get(var);
			System.out.println(" var: " + var + "   val: " + val);
		    }
		}
	    } catch (Exception e) {
		System.out.println("error: " + e);
		e.printStackTrace();
	    }
	}
    }
}


/*The prologtokenizer breaks a string in such pieces that are usefull
for parsing. It searches for constants, numbers, or special operators,
and else it returns the characters one by one.
It ignores spaces, tabs,enters and %comment.*/

class prologtokenizer {
    String unused;/*the unprocessed part of the string*/
    Vector tokens;/*the allready extracted tokens*/
    int cursor;/*the current position in the token vector.*/

    static String normalchar=
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz1234567890";
    static String opchar="+-*/\\^<>=`~:.?@#$&";
    static String numchar="1234567890";

    boolean splitoff() {
        /*extract a token from unused, and adds it to tokens*/
        /*step 1: skip whitespace
          2: decide on first character what the token kind is.
          3: seek the end of the token (start)
          4: shorten unused, add the token, return true;*/
        if(unused==null)            return false;
        int max=unused.length();
        int start=0;
        boolean comment=false;
        for(start=0;start<max;start++) {
            if(unused.charAt(start)=='%')
                comment=true;
            else if(unused.charAt(start)=='\n')
                comment=false;
            if(!comment&&unused.charAt(start)>32)
                break;
        }
        if(start==max) {
            unused=null;return false;
        }
        StringBuffer buf=new StringBuffer();
        char d;
        char c=unused.charAt(start);
        start++;
        buf.append(c);
        if(c==39||c=='"') {
            boolean closed=false;
            for(;start<max;start++) {
                d=unused.charAt(start);
                if(d==c) {
                    start++;
                    if(start<max&&unused.charAt(start)==c);//mind the ;
                    else
                        {closed=true;break;}
                }
                buf.append(d);
            }
            if(!closed)
                return false;
        }
        else
            if(c=='\"') {
                boolean closed=false;
                for(;start<max;start++) {
                    d=unused.charAt(start);
                    if(d==c) {
                        start++;
                        if(start<max&&unused.charAt(start)==c);//mind the ;
                        else
                            {buf.append(d);closed=true;break;}
                    }
                    buf.append(d);
                }
            }
            else if(in(c,numchar)) { //number
                for(;start<max;start++) {
                    d=unused.charAt(start);
                    if(!in(unused.charAt(start),numchar))
                        break;
                    buf.append(d);
                }
            }  else if(in(c,opchar)) { //a special operator
                for(;start<max;start++) {
                    d=unused.charAt(start);
                    if(!in(unused.charAt(start),opchar))
                        break;
                    buf.append(d);
                }
            } else if(in(c,normalchar)) {//normal constant
                for(;start<max;start++) {
                    d=unused.charAt(start);
                    if(!in(unused.charAt(start),normalchar))
                        break;
                    buf.append(d);
                }
            }

        tokens.addElement(buf.toString());
        unused=unused.substring(start);
        return true;
    }

    public prologtokenizer(String s) {
        unused=s;
        cursor=0;
        tokens=new Vector();
    }

    public term gettermdot(Thread t) {
        /*get a term, closed by a . (dot or period).*/
        term t1=term.getTerm(this);
        if(t1!=null&&".".equals(gettoken()))
            return t1;
        return null;
    }

    char get0() {
        /*get a single character.*/
        char c='*';
        if(unused!=null&&unused.length()>0) {
            c=unused.charAt(0);
            unused=unused.substring(1);
        }
        return c;
    }

    public boolean more() {
        /*do we have more tokens?*/
        if(cursor<tokens.size())
            return true;
        return splitoff();
    }
    public String peek() {
        /*returns the first token, but does not remove it.*/
        if(cursor>tokens.size())
            return null;
        if(cursor==tokens.size())
            if(!splitoff())return null;
        return (String)tokens.elementAt(cursor);
    }
    public String gettoken() {
        /*removes a token out of this tokenizer, and returns that token*/
        if(!more())
            return null;
        cursor++;
        return (String)tokens.elementAt(cursor-1);
    }
    int getpos()/*return the position in the tokenvector*/
    {return cursor;}
    void jumpto(int i)/*jump to a position in the tokenvector*/
    {cursor=i;}

    static boolean in(char c,String s) {
        /*tells wether a char is in a string.*/
        for(int i=s.length()-1;i>=0;i--)
            if(c==s.charAt(i))
                return true;
        return false;
    }
}

/**********************************************************
 *  T E R M
 **********************************************************/

class term {
    int type;
    public final static int EQ=211,OPEN=212,NUMBER=213,FUNCTOR=214;
    String name;//the functor or constant name.
    String varname;//the name this term would have as a variable
    String qname;/*the name with quotes, if necessary.*/
    int arity;//the number of arguments in a functor.
    term[] arg;//the arguments in case of functor;

    public final static int MAXARG=12;//the maximum number of arguments
    static term emptylist;//the unique empty list
    static String varstart="_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static String normalstart=
        "abcdefghijklmnopqrstuvwxyz'+-*/\\^<>=`~:.?@#$&";
    static String numchar="1234567890";
    static int NaN=Integer.MIN_VALUE;/*Not a Number*/

    term() { /*make anonymous variable*/
        type=OPEN;
        arity=0;
    }
    term(String s) { /*named variable*/
        type=OPEN;
        arity=0;
        varname=s;
    }
    term(prologop pre1,term t) { /*unary operator*/
        type=FUNCTOR;
        name=pre1.name;
        qname=getqname(name);
        arity=0;
        addarg(t);
    }
    static term newconstant(String n)
    {return newconstant(n,getqname(n));}
    static term newconstant(String n,String qn) {
        /*make a constant (for example abc)*/
        term t=new term();
        t.type=FUNCTOR;
        t.name=n;
        t.qname=qn;
        return t;
    }

    static String getqname(String inp)
    /*decides wether a name should be quoted.*/
    {if(inp.length()!=0&&
        prologtokenizer.in(inp.charAt(0),normalstart))  {
        boolean simple1=true,simple2=true;
        for(int i=0;i<inp.length();i++)
            if(!prologtokenizer.in(inp.charAt(i),
                                   prologtokenizer.normalchar))
                {simple1=false;break;}
        if(!simple1)
            for(int i=0;i<inp.length();i++)
                if(!prologtokenizer.in(inp.charAt(i),
                                       prologtokenizer.opchar))
                    {simple2=false;break;}
        if(simple1||simple2)
            return inp;
    }
    return "'"+inp+"'";
    }

    term(term t,prologop in1,term t2) { /*infix operator*/
        type=FUNCTOR;
        name=in1.name;
        qname=getqname(name);
        arity=0;
        addarg(t);
        addarg(t2);
    }
    term(int n) { /*number*/
        type=NUMBER;
        arity=n;
    }

    static term asciilist(String s) {
        /*make a list of asciivalues*/
        term t=emptylist;
        for(int i=s.length()-1;i>=0;i--)
            t=makelist(new term((int)s.charAt(i)),t);
        return t;
    }

    static String readasciilist(term t) {
        /*make a string from a list of asciivalues*/
        StringBuffer buf=new StringBuffer();
        term num;
        t=skipeq(t);
        while(t.name!=emptylist.name) {
            if(t.type!=t.FUNCTOR||t.name!=prologop.listcons.name)
                return null;
            num=skipeq(t.arg[0]);
            if(num.type!=NUMBER||num.arity<0||num.arity>255)
                return null;
            buf.append((char)num.arity);
            t=skipeq(t.arg[1]);
        }
        return buf.toString();
    }

    static term makelist(term head,term tail)
    {return new term(head,prologop.listcons,tail);}

    void functor(String s)/*make this term a functor*/
    {functor(s,getqname(s));}
    void functor(String s,String qs) { /*make this term a functor*/
        type=FUNCTOR;
        name=s;
        qname=qs;
        arity=0;
    }

    void addarg(term g) { /*add an argument to this functor*/
        if(arg==null)
            arg=new term[MAXARG];
        arg[arity]=g;
        arity++;
    }

    static void is(term x,term y) {
        /*instatiate X to being the same as Y. */
        if(x==y)
            return;
        x.arity=0;
        x.type=EQ;
        x.addarg(y);
    }

    static term skipeq(term t)
    {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -