User Defined Functions

1 view
Skip to first unread message

Rangarajan Krishnamoorthy

unread,
Nov 17, 2018, 12:52:38 AM11/17/18
to ErgoAI-Flor...@coherentknowledge.com
Hi,
I am trying to understand UDF. 

1) What is the difference, if any, between the following two definitions?

\udf foo(?a^^MyType) := <Body>.

\udf foo(?a:MyType) := <Body>.


2) Can these co-exist (in the same module)?

Regards,
Rangarajan

Michael Kifer

unread,
Nov 17, 2018, 3:18:02 AM11/17/18
to ErgoAI, Flora-2, and XSB Users Forum
Not sure what you meant by co-existence.
What you probably wanted is this:

 \udf moo1(?a) := ?c \if p(?a^^MyType,?c).
\udf moo2(?a) := ?c \if p(?a:MyType,?c).

p(abc:MyType, cde).
p(dfg,xvc).

?- moo1(?X)=?R, writeln(test1m=?X+?R)@\io.
?- moo2(?X)=?R, writeln(test2m=?X+?R)@\io.

In general, ?X^^type restricts ?X to bindings that are members of class type, but if ?X remains unbound then no checks are made. 
In particular, one cannot use ?X^^type to query the class type because ?X^^type does not bind ?X to anything. This form only check is the current binding for ?X is in type.
?X:type behaves similarly if ?X is bound, but if it isn't then ?X will successively get bound  to every member of type.  If the latter is what you want then ?X:type should be used. 
But if ?X always gets bound somewhere then ?X^^type can be more efficient, especially if the class type is large.   
Also, evaluation of p(?X^^type) is delayed if ?X is not bound, so something like  ... p(?X^^type), q(?X)  will be evaluated efficiently, if q binds ?X to a small number of values. 
In a similar situation, ?X:type, p(?X), q(?X)  would be much slower, if type is much larger than q (because of all the extra bindings that ?X:type will make, and most of them will be rejected by q).
In other words,  p(?X^^type), q(?X) will behave more or less like  q(?X), ?X:type, p(?X).

Now, regarding the actual form of the udf that you asked about:
        \udf foo1(?a^^MyType) := ?c \if p(?a,?c).
it is equivalent to
        \udf foo1(?a) := ?c \if p(?a^^MyType,?c).

But this form
        \udf foo2(?a:MyType) := ?c \if p(?a,?c).
is the same as
        \udf foo2(?a) := ?c \if p(?a,?c).
        \udf ?a:MyType :- p(?a,?c).
because the embedded ... : ...  in a rule head or in udf head, like in foo2(?a:MyType) here,   always treats ?a:MyType as a conjunct that stays in the rule head.
This is not what one wants in this particular case.

The parser should really prohibit this form of a udf definition.
Reply all
Reply to author
Forward
0 new messages