I am not really sure how to go about giving the procedural and declarative reading of facts and predicates. I was wondering if anyone could give me some guidance on how to write them.
Here is my code for inserting a Key
into a binary tree:
insert(Key, null, tree(key, null, null)).
insert(Key, tree(Root, LST, RST), tree(Root, NewLST, RST)) :-
Key < Root,
insert(Key, LST, NewLST).
insert(Key, tree(Root, LST, RST), tree(Root, LST, NewRST)) :-
Key > Root,
insert(Key, RST, NewRST).
Note: There are bugs with OP code in the question for a binary tree. The question was for the reading of the Prolog code not the fixing of the code.
Procedural reading based on Bratko, Section 9.3
Insertion and deletion in a binary tree
pg. 231T
is a binary tree. A tree can be empty, have only a root, have one leaf, or have two leafs.Procedural reading:
The result of inserting
Key
to the empty treenull
is the treetree(key,null,null)
.Proceduralreading:
If the root of
T
is greater thanKey
then insertKey
into the left subtree ofT
.Procedural reading:
If the root of
T
is less thanKey
then insertKey
into the right subtree ofT
.Declarative reading based on The Art of Prolog, Section 3.4
Binary Trees
pg. 72Declarative reading:
Key
can be inserted into a null treeKey
is a less than the value at nodeKey
is a greater than the value at node.A personal note on why writing the declarative meaning is important.
When trying to understand the procedural meaning, for me it explains how the code works in the procedural mode where the input parameters are set and a value is returned.
Note: I fixed a bug with the OP code to get that query to work as demonstarted.
or
When trying to understand the declarative meaning, for me it explains how the code works in other modes where the result is given and one or more of the parameters are variables, or all of the parameters are variables (can't remember what this is called, I think it is most general question).
In this case when writing the declarative meaning, and trying queries like
and
tells me that one or more of these need to be addressed:
So by learning how to add modes to code to go from procedural to declarative, one can also look in the reverse of how can this can help to write better code in procedural languages.
When I write code for programming languages that do not have algebraic data types as a first class notion such as Java I have to use many
if
orswitch
statements to cover all of the combinations of the data structure. Now there are cases where the code runs correctly with out anelse
ordefault
but to make the code better when I write anif
orswitch
, I always add theelse
ordefault
withassert (false)
and run the code. If the assert fails it typically indicates that my reasoning about the code was wrong, and I either rewrite the code or change the assert to a comment explaining why theelse
ordefault
case can occur but is not needed.