Primitive Recursive Functions are a way to define elementary math functions using only a few simple operations.
Because AIML has no built-in math functions, writing simple addition and subtraction functions is a minor challenge. Generally, for things like math functions, we would recommend breaking out of AIML and using another language through the <system> tag. But as an exercise, you can define addition and subtraction in AIML using primitive recursive functions.
First you need to be able to count. The function SUCCESSOR(X) returns X+1. In AIML we can define the SUCCESSOR function with a group of categories:
<category><pattern>SUCCESSOR 0</pattern><template>1</template></category>
<category><pattern>SUCCESSOR 1</pattern><template>2</template></category>
<category><pattern>SUCCESSOR 2</pattern><template>3</template></category>
<category><pattern>SUCCESSOR 3</pattern><template>4</template></category>
<category><pattern>SUCCESSOR 4</pattern><template>5</template></category>
<category><pattern>SUCCESSOR 5</pattern><template>6</template></category>
<category><pattern>SUCCESSOR 6</pattern><template>7</template></category>
<category><pattern>SUCCESSOR 7</pattern><template>8</template></category>
<category><pattern>SUCCESSOR 8</pattern><template>9</template></category>
<category><pattern>SUCCESSOR 9</pattern><template>1 0</template></category>
Notice that when we got to 10, we had to write the number as “1 0” rather than “10”, due to the pattern matching style of AIML.
For two digit numbers we need a special case when the last digit is 9. We can build the SUCCESSOR function for two digits from the one-digit version:
<category><pattern>SUCCESSOR * 9</pattern>
<template><srai>SUCCESSOR <star/></srai> 0</template>
</category>
<category><pattern>SUCCESSOR * *</pattern>
<template><star/> <srai>SUCCESSOR <star index="2"/></srai>
</template>
</category>
For three digits, we can write:
<category><pattern>SUCCESSOR * 9 9</pattern>
<template><srai>SUCCESSOR <star/></srai> 0 0</template>
</category>
<category><pattern>SUCCESSOR * * *</pattern>
<template><star/> <srai>SUCCESSOR <star index="2"/> <star index="3"/></srai>
</template>
</category>
Now we have the ability to count from 0 to 999.
Adding 0 to a number is the same as the number itself:
<category>
<pattern>ADD 0 PLUS *</pattern>
<template><star/></template>
</category>
The function ADD(1, X) is the same as the function SUCCESSOR(X):
<category>
<pattern>ADD 1 PLUS *</pattern>
<template><srai>SUCCESSOR <star/></srai></template>
</category>
The ADD(X,Y) function breaks down the operation of adding into a series of ADD(X, 1), repeated recursively Y times:
<category>
<pattern>ADD * PLUS *</pattern>
<template><srai>ADD 1 PLUS <srai>ADD <srai>PREDECESSOR <star/></srai> PLUS <star index="2"/></srai></srai>
</template>
</category>