Prolog List Examples

Prolog List Examples

Prolog List Examples
Prolog List Examples


Implement following prolog programs based on list.

  1. To display first element of a list.
  2. To display last element of a list.
  3. To count number of elements in a list.
  4. To count odd and even elements of a list.

1. To display first element of a list.

Program:

firstEl([FIRST|_], FIRST):-
    write("\n first element is : "),
    write(FIRST).

Output:

?- firstEl([1,2,3,4,5,6,7],FIRST).
first element is : 1
FIRST = 1.

?- firstEl([2,4,7,1],FIRST).
first element is : 2
FIRST = 2.

2. To display last element of a list.

Program:

lastEl([X],X).
lastEl([_|T],Y):-lastEl(T,Y).

Output:

?- lastEl([1,2,3,4,5,6,7],X).
X = 7.

?- lastEl([3,2,1],X).
X = 1.

3. To count number of elements in a list.

Program:

size([],0).
size([_|T],N):-size(T,N1),N is N1+1.

Output:

?- size([1,2,3,4,5,6,7],X).
X = 7.

?- size([2,4,11],X).
X = 3.

4. To count odd and even elements of a list.

Program:

evenlength:-
 write('even elements in the list').
oddlength:-
 write('odd elements in the list').

oddeven([H|T]):-
 length(T,L),
 L>=0 ->
 (
  L1 is L+1,
  L2 is mod(L1,2),
  L2=:=0 ->
   evenlength
  ;
   oddlength
 ).

Output:

?- oddeven([1,2,3,4,5,6,7]).
odd elements in the list
true.

?- oddeven([1,2,3,4,5,6]).
even elements in the list
true.

Comments

Post a Comment