My January 21 post described a simplified poker game implemented as a tuProlog program with a library of custom Java predicates.

Here are two random number predicates from the HurricanePoker custom Java library:

  public boolean random_int_2(Term val0, Term arg1) throws Throwable {
    if (!(val0 instanceof Number)) {
      return false;
    }
    if (!(arg1 instanceof Var)) {
      return false;
    }
    int n = ((alice.tuprolog.Number) val0).intValue();
    java.lang.Double d = new java.lang.Double(1 + (Math.random() * n));
    return (unify(arg1, new alice.tuprolog.Int(d.intValue())));
  }

  public boolean random_double_1(Term arg0) {
    if (!(arg0 instanceof Var)) {
      return false;
    }
    return (unify(arg0, new alice.tuprolog.Double(Math.random())));
  }

These are accessed from Prolog as follows, returning their results into the unbound variables P and RR:

  . . .
  	random_int(8, P),
	random_double(RR),
  . . .

I read more of the tuProlog documentation and decided to simplify these by converting them into functors. Here are the results:

  public Term random_int_1(Term val0) throws Throwable {
    Term result = new Var();
    if (!(val0 instanceof Number)) {
      throw new Exception("random_int requires a bound integer parameter.");
    }
    int n = ((alice.tuprolog.Number) val0).intValue();
    java.lang.Double d = new java.lang.Double(1 + (Math.random() * n));
    unify(result, new alice.tuprolog.Int(d.intValue()));
    return result;
  }

  public Term random_double_0() {
    Term result = new Var();
    unify(result, new alice.tuprolog.Double(Math.random()));
    return result;
  }

Now they are invoked in Prolog as follows, using the is single assignment operator:

  . . .
  	P is random_int(8),
	RR is random_double,
  . . .

These two Prolog statements more closely match the style of true functional programming languages. This contrasts with the somewhat idiosyncratic unification feature used by the Prolog predicate versions of these random number generators.

Advertisements