04-07-2009
|
#6
|
[KAPLAN]
|
Cevap : Prolog Örnekleri | Prolog Examples
Lecture 8
Program 8 1 - appending two lists to make a third - or splitting a list into two lists
/* ************************************************ */
/* */
/* app/3 */
/* Summary: True if Arg 3 is Arg 2 appended to */
/* Arg 1 */
/* Arg 1: List */
/* Arg 2: List */
/* Arg 3: List */
/* Author: P J Hancox */
/* Date: 29 October 1999 */
/* */
/* ************************************************ */
% 1 - terminating
app([], List, List)
% 2 - recursive
app([Hd|L1],L2,[Hd|L3]) :-
app(L1, L2, L3)
Program 8 2 - is an element a member of a list?
/* ************************************************ */
/* */
/* memb/2 */
/* Summary: True if Arg1 is in Arg2 */
/* Arg 1: Term */
/* Arg 2: List */
/* Author: P J Hancox */
/* Date: 22 October 1999 */
/* */
/* ************************************************ */
% 1 - terminating
memb(Elem, [Elem|_])
% 2 - recursive
memb(Elem, [_|Tail]) :-
memb(Elem, Tail)
Program 8 3 - updating a count of a letter
/* ************************************************ */
/* */
/* update_count/3 */
/* Summary: Increments Arg3 is Arg1 is "a" */
/* Arg 1: Vowel */
/* Arg 2: Number (accumulator) */
/* Arg 3: Number */
/* Author: P J Hancox */
/* Date: 22 October 1999 */
/* */
/* ************************************************ */
% 1 - a
update_count(a, A, A1) :-
A1 is A + 1
% 2 - not "a"
update_count(Letter, A, A) :-
Letter \== a
Program 8 4 - inefficient factorial
/* ************************************************ */
/* */
/* fac1/2 */
/* Summary: True if Arg2 is the factorial of */
/* Arg1 */
/* Arg 1: Number */
/* Arg 2: Number */
/* Author: P J Hancox */
/* Date: 22 October 1999 */
/* */
/* ************************************************ */
% 1 - terminating
fac1(0, 1)
% 2 - recursive - but goes into infinite recursion
% on backtracking
fac1(N, Factorial) :-
N1 is N - 1,
fac1(N1, Factorial1),
Factorial is N * Factorial1
Program 8 5 - more efficient factorial - using accumulator
/* ************************************************ */
/* */
/* fac2/2 */
/* Summary: True if Arg2 is the factorial of */
/* Arg1 Calls fac2/3 */
/* Arg 1: Number */
/* Arg 2: Number */
/* Author: P J Hancox */
/* Date: 22 October 1999 */
/* */
/* ************************************************ */
fac2(Numb, Fact) :-
fac2(Numb, 1, Fact)
/* ************************************************ */
/* */
/* fac2/3 */
/* Summary: True if Arg3 is the factorial of */
/* Arg1 */
/* Arg 1: Number */
/* Arg 2: Number (accumulator) */
/* Arg 2: Number */
/* Author: P J Hancox */
/* Date: 22 October 1999 */
/* */
/* ************************************************ */
% 1 - terminating
fac2(0, Fact, Fact)
% 2 - recursive - but goes into infinite recursion
% on backtracking
fac2(N, Accum, Fact) :-
N1 is N - 1,
tab(N1), write(Accum), nl, % we can output this
Accum1 is N * Accum,
fac2(N1, Accum1, Fact)
|
|
|