Article View: comp.lang.prolog
Article #1055Re: Simple Prolog Question
From: Richard A. O'Keefe
Date: Fri, 10 Aug 1990 08:18
Date: Fri, 10 Aug 1990 08:18
50 lines
2072 bytes
2072 bytes
In article <2157@cernvax.UUCP>, julian@cernvax.UUCP (julian bunn) writes:
> I am trying to write a program that will remove leading blank
> characters from a list.
You're clearly not using the QP library, because it's all there...
> remove_blanks([H|T],T) :- H=32, remove_blanks(T,_).
> remove_blanks(S,S).
(a) Let's look at that first clause, and let's consider the case
where you called remove_blanks(" sargon", Ans).
This unifies with the head of the first clause, giving
H = (0' ) = 32
T = " sargon"
Ans = T = " sargon"
the body becomes
32 = 32, remove_blanks(" sargon", _dont_dare_tell_me_this_answer_)
the first goal of which succeeds, and then your recursive call says
'discard leading blanks from " sargon" AND THEN THROW AWAY THE
ANSWER'
So you want your first clause to be
remove_blanks([0' |T], Answer) :- remove_blanks(T, Answer).
(b) The second clause will _also_ succeed in this case, with
S = " sargon"
Answer = S = " sargon".
You presumably don't want this to happen.
A pure way of doing it is
remove_leading_blanks([], []).
remove_leading_blanks([H|T], [H|T]) :- H =\= " ".
remove_leading_blanks([H|T], R ) :- H =:= " ",
remove_leading_blanks(T, R).
If you don't mind a red cut, you can do
remove_leading_blanks([32|T], R) :- !,
remove_leading_blanks(T, R).
remove_leading_blanks(T, R).
(I changed the name to remove_leading_blanks/2 because it doesn't remove
^^^^^^^
_all_ blanks as the name suggests; trailing blanks and consecutive
internal blanks are left alone.)
--
Taphonomy begins at death.
Technical Details
Message-ID:
<3542@goanna.cs.rmit.oz.au>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!zaphod.mps.ohio-state.edu!samsung!munnari.oz.au!goanna!okReferences:
<2157@cernvax.UUCP>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!zaphod.mps.ohio-state.edu!samsung!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.lang.prolog Subject: Re: Simple Prolog Question Message-ID: <3542@goanna.cs.rmit.oz.au> Date: 10 Aug 90 08:18:42 GMT References: <2157@cernvax.UUCP> Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 50