logo

Logic Programming: List Head and Tail Represented in Dot Notation

   

Added on  2023-04-21

4 Pages828 Words364 Views
Logic Programming
1. List Head and Tail Represented in Dot Notation.
Given that:
Elements of a list are items between the Outermost Square brackets separated by commas,
The head is the first Element in the list, and that everything else forms the tail,
Then:
(i) [tennis,cricket,[rowing,rafting]]
Head = tennis,
Tail = [cricket, [rowing, rafting]]
dot notation:
Head = tennis
Tail = .(cricket,.(.(rowing,.(rafting,[])),[]))
(ii) [[screwdriver,brace],hammer,hacksaw]
Head = [screwdriver, brace],
Tail = [hammer, hacksaw]
dot notation:
Head = .(screwdriver,.(brace,[]))
Tail = .(hammer,.(hacksaw,[]))
(iii) [[electric],[petrol,diesel,[hybrid]]]
Head = [electric],
Tail = [[petrol, diesel, [hybrid]]]
dot notation:
Head = .(electric,[])
Tail = .(.(petrol,.(diesel,.(.(hybrid,[]),[]))),[])
Logic Programming: List Head and Tail Represented in Dot Notation_1
2. Prolog Program
check([ ], 0).
check([H | T], S) :- check(T, TS) , S is TS + H.
(i) How the above Prolog Program Works
The first line is a fact; returns 0 on an empty list.
This fact will be used to terminate the rule’s execution recursion.
The second line is a rule that states:
if there exists T, TS such that TS + H results to S, then:
there also exists a list (with head and tail) that results in S
In other words,
this Recursively adds consecutive items in a given list.
Thus, S will be the Sum of all Items in that given list.
The Summation continues until there is no item left to add, thus check([ ], 0). will be true)
Logic Programming: List Head and Tail Represented in Dot Notation_2

End of preview

Want to access all the pages? Upload your documents or become a member.