Re: simple list recursion
From: W (wgw)
Date: 05/10/04
- Next message: Bill Spight: "Re: append"
- Previous message: Torkel Franzen: "Re: output **no What's wrong here?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 10 May 2004 07:45:42 -0700
Your class is probably over, but the pedagogical purpose behind this was to
get you to realize that you need to add a condition to when you included the
head of the list: (the fact that strings are represented as lists should not
be the focus of your attention -- that is a pedagogical error):
filter(_,[],[]). % of course the base case.
filter(A,[A|T], R) :- filter(A,T,R). % notice the use of unification to
check ANY item in list, then just recurse on the rest of the list.
filter(A,[H|T], [H|R]) :- %this time put the head on
A \= H, %have to make sure they are not the same
(ie not unifiable)
filter(A,T,R).
for one simple condition where you are testing the case "unifies" or "does
not unify" you could use the if-then-else syntactic sugar, or throw in a cut
in clause 2 and leave out the check for "does not unify" in clause 3.
In your code, you did not check for non-unification, so you could backtrak
into your solution many times.
also, you don't need to append the empty list on front in clause2 since it
does nothing.
Hope you enjoyed the course.
W
"Martin Fuchs" <usenet-ng@gmx.net> wrote in message
news:c5jc3c$2a5db$1@ID-134512.news.uni-berlin.de...
> (I didn't use Prolog very often yet.)
>
> I've got a predicate "conc" concatenating two strings (or lists in
general).
>
> conc("",B,B).
> conc([H|T],B,[H|R]):- conc(T,B,R).
>
> Now I want to define a predicate "filter" which removes single characters
from
> strings, e.g.
>
> filter("A","OASIS","OSIS").
>
> My idea was as follows, but it doesn't work...
>
> filter(_,"","").
> filter(A,[H|T],R):- conc("",A,H),filter(A,T,R).
> filter(A,[H|T],[H|R]):- conc(A,T,R).
>
>
> What's my stupid mistake?
>
>
> Thanks
> mf
- Next message: Bill Spight: "Re: append"
- Previous message: Torkel Franzen: "Re: output **no What's wrong here?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|