Let's say i have list Xs = [a,b,c].
Now i want to iterate through all elements and call another function for this elements. My question is: how to do this using head and tail? I would be grateful for help.
Generally, you do not iterate in Prolog. Instead, you write a rule with a pair of recursive clauses, like this: dosomething([]). dosomething([H|T]) :- process(H), dosomething(T).
Example #1append( [X | Y], Z, [X | W]) :- append( Y, Z, W). Input: append([1,2],[3,4,5], X). In the above example of by using append, the code has been written, by performing steps append the third list from two lists, where we can say if X=[1, 2], Y=[3, 4, 5], and Z is the joining of X and Y which is the third list.
Prolog in Artificial Intelligence It is a data structure that can be used in different cases for non-numeric programming. Lists are used to store the atoms as a collection. In the subsequent sections, we will discuss the following topics − Representation of lists in Prolog.
Generally, you do not iterate in Prolog. Instead, you write a rule with a pair of recursive clauses, like this:
dosomething([]).
dosomething([H|T]) :- process(H), dosomething(T).
The first clause processes the base case, when the list []
is empty. In this case, there is nothing to do, so the body of the rule is empty as well.
The second clause processes the case when your list has at least one element. Syntax [H|T]
unifies with your list in such a way that H
becomes the head of the list, and T
becomes its tail. For example, if you process dosomething([a,b,c])
, H
becomes a
, and T
becomes [b,c]
.
The body of this rule has two parts. The first part operates on the head, calling process
on it. This is the rule that you want executed for each element of the list. The second part invokes dosomething
rule recursively on the tail of the list. When the tail list is not empty, the second clause of dosomething
would unify with the shorter list to continue processing. When the tail list is empty, the first clause would unify, thus ending the processing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With