Arithmetic expressions in Prolog are actually stuctures with infix functors . Try the following expressions:
?- Expr = 1 + 2 * 3 + 4. ?- Expr = (a + 5) / b.
Prolog will not evaluate expressions unless it is explicitly forced to.
The built-in operator, is, will force an arithmetic structure to be evaluated. Try these:
?- Expr is 1 + 2 * 3 + 4. ?- Expr is (1 + 2) * (3 + 4). ?- Expr is 10.
When is is used on a structure which cannot be calculated an error will be printed. For example:
?- Expr is (a + 5) / b . ERROR: Arithmetic: `b/0’ is not a function ?- Expr is 1 + 2 * 3 + X . ERROR: Arguments are not sufficiently instantiated
Add a predicate, listCount(List, Count), to family.pl which will count the elements of the list. This will be a recursive predicate. This base case is for an empty list which has zero elements. The recursive case should add one to the count of the Tail. Write the listCount predicate then try it out:
?- listCount([], Count). Count = 0 ?- listCount([a, b, c], Count). Count = 3 ?- listCount([1, [2, 3], [[4], 5], 6], Count). Count = 4
Use listCount and findall to write a predicate, countDescendants(Person, Count) which calculates how many descendants Person has.
?- countDescendants(albert, Count). Count = 9
Write a new version of listCount, called deepListCount which counts all elements in the list and embedded lists. Try to do it without using cuts. Here is some sample output:
?- deepListCount([], Count). Count = 0 ?- deepListCount([a, b, c], Count). Count = 3 ?- deepListCount([[a, b, c]], Count). Count = 3 ?- deepListCount([a, [b, c], [[d], e], f], Count). Count = 6
To get you started, here is a rule that returns 1 for anything that is not a list:
deepListCount(A, 1) :- \+ is_list(A). % A is not a list
Resource created Saturday 06 February 2021, 09:11:01 PM.