newbie - Prolog, lists, recursion
From: o (dcsmpayne_at_bigpond.com)
Date: 11/04/03
- Next message: o: "Re: newbie - Prolog, lists, recursion"
- Previous message: Ulrich Furbach: "ANN: ECCAI AI Dissertation Award"
- Next in thread: o: "Re: newbie - Prolog, lists, recursion"
- Reply: o: "Re: newbie - Prolog, lists, recursion"
- Reply: Matthew Purver: "Re: newbie - Prolog, lists, recursion"
- Reply: o: "Re: newbie - Prolog, lists, recursion"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 04 Nov 2003 09:55:11 GMT
Hi all,
I am hoping the list can help me understand lists & recursion better, I have
read quite a few tuts but none start at an "elementary" enough level for me
when it comes to lists. However, it may be the way Prlog predicates may be
read/written both ways - this statement sounds dumb - I hope you will see
what I mean as we go through an example I am working on.
I am working on a predicate to count the number of even numbers in a list. I
have created a predicate count_even /3 (see below) ... I would rather it be
count_even /2
%
% Print the even numbers contained in a list.
%
% derived from a problem to COUNT the number of even digits in a number.
% hence the count_even name for the file!
%
% base case
count_even(1,N,[N|_]):- (I understand this to mean the H is @ element 1)
A is mod(N,2),
A = 0.
% recursive case
count_even(Cnt,N,[_|T]):-
count_even(Cnt,N,T),
N1 is Cnt - 1,
N2 is mod(N1,2),
N2 = 0.
%
The output produced is ...
1 ?- count_even(P,N,[1,2,3,4,5,6,7,8]).
P = 1
N = 2 ;
P = 1
N = 4 ;
P = 1
N = 6 ;
P = 1
N = 8 ;
No
Now clearly I have only written a predicate to identify each even number and
display it. Notice I have also used the Cnt function (I think this is a
built-in counter function) to allow me to traverse the list. Surely there is
a better way! Surely this can be done without Cnt. Have I created an example
of Head recursion?
I have many other questions, I hope I don't become a pest - any assistance
gratefully accepted.
regards
Darren
- Next message: o: "Re: newbie - Prolog, lists, recursion"
- Previous message: Ulrich Furbach: "ANN: ECCAI AI Dissertation Award"
- Next in thread: o: "Re: newbie - Prolog, lists, recursion"
- Reply: o: "Re: newbie - Prolog, lists, recursion"
- Reply: Matthew Purver: "Re: newbie - Prolog, lists, recursion"
- Reply: o: "Re: newbie - Prolog, lists, recursion"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|