TUTORIAL 6 of Artificial Intelligence
a. Write a program to find the position of an element from the given list.
domains
symbollist
= symbol*
predicates
list_getpos(symbol,symbollist)
getpos(symbol,symbollist,integer)
clauses
list_getpos(X,SymList):-
P = 0,
getpos(X,SymList,P).
getpos(S,[S|_],P):-
write("Position
is : "),
write(P),nl.
getpos(S,[Head|Tail],P):-
PP = P + 1,
getpos(S,Tail,PP).
b. Write a program to append a list by adding at the front and the last of
the list.
domains
symbollist
= symbol*
predicates
print_list(symbollist)
list_append(symbollist,symbollist)
append(symbollist,symbollist,symbollist)
clauses
print_list([]).
print_list([Head|Tail]):-
write(Head),write("
"),
print_list(Tail).
list_append(SymList1,SymList2):-
append(SymList1,SymList2,Appended),
append(Appended,Symlist1,FinalAppended),
write("Appended
list : [ "),
print_list(FinalAppended),
write("]"),nl.
append([],SymList2,SymList2).
append([Head|Tail1],SymList2,[Head|Tail2]):-
append(Tail1,SymList2,Tail2).
C. Write a program to find the minimum and
maximum from the given list of numbers.
domains
numlist
= integer*
predicates
list_get_minmax(numlist,integer,integer)
get_minmax(numlist)
get_min(numlist,integer,integer)
get_max(numlist,integer,integer)
clauses
get_minmax(NumList):-
list_get_minmax(NumList,Min,Max),
write("Minimum
is : "),write(Min),nl,
write("Maximum
is : "),write(Max),nl.
list_get_minmax([Head|Tail],Min,Max):-
get_min([Head|Tail],Head,Min),
get_max([Head|Tail],Head,Max).
get_min([],PrevMin,MinAns):-
MinAns
= PrevMin.
get_min([Head|Tail],PrevMin,MinAns):-
Head
< PrevMin,
get_min(Tail,Head,MinAns).
get_min([Head|Tail],PrevMin,MinAns):-
Head
>= PrevMin,
get_min(Tail,PrevMin,MinAns).
get_max([],PrevMax,MaxAns):-
MaxAns
= PrevMax.
get_max([Head|Tail],PrevMax,MaxAns):-
Head
> PrevMax,
get_max(Tail,Head,MaxAns).
get_max([Head|Tail],PrevMax,MaxAns):-
Head
<= PrevMax,
get_max(Tail,PrevMax,MaxAns).