Newsgroups: comp.lang.prolog
Path: cantaloupe.srv.cs.cmu.edu!bb3.andrew.cmu.edu!nntp.sei.cmu.edu!cis.ohio-state.edu!math.ohio-state.edu!usc!chi-news.cic.net!nntp.coast.net!harbinger.cc.monash.edu.au!news.rmit.EDU.AU!news.unimelb.EDU.AU!munnari.OZ.AU!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
From: fjh@munta.cs.mu.OZ.AU (Fergus Henderson)
Subject: Re: help
Message-ID: <9536312.27877@mulga.cs.mu.OZ.AU>
Sender: news@cs.mu.OZ.AU (CS-Usenet)
Organization: Computer Science, University of Melbourne, Australia
References: <4bqcfs$8h7@lantana.singnet.com.sg> <4brqvn$frm@damage.usa1.net>
Date: Fri, 29 Dec 1995 01:19:08 GMT
Lines: 35

ray@usa1.com (ray@usa1.com) writes:

>chiach@merlion.singnet.com.sg says...
>>
>>Help, anybody knows how to extract the last item of a list using Prolog.
[...]
>last([X],X).
>last([_|Y],X):- last(Y,X).

One of the drawbacks of Prolog is that the language makes it very
easy to write inefficient code.  On nearly all Prolog systems,
that code will leave an unnecessary choice point around.  Now the
extra time required to create the choice point, although regretable,
is not so important.  But the space cost might be very significant
indeed - it could turn a program that consumes a small, bounded amount
of memory into a program whose memory requirements are unbounded.
(C programmers aren't the only ones that have to worry about memory leaks!)

You can avoid this problem by writing the code like this instead.

	last([X|Xs], Last) :- last_2(Xs, Last, X).

	last_2([], Last, Last).
	last_2([X|Xs], Last, _) :- last_2(Xs, Last, X).

Once you become concious of the problem, it is not too hard to avoid
writing code that creates unnecessary choice-points.  But in a large
project with many developers, it can be quite difficult to make sure
that everyone does this at all times. 

The usual solution seems to be to liberally sprinkle the code with cuts.

--
Fergus Henderson             	WWW: http://www.cs.mu.oz.au/~fjh
fjh@cs.mu.oz.au              	PGP: finger fjh@128.250.37.3
