Newsgroups: comp.lang.lisp
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!oitnews.harvard.edu!yale!yale.edu!spool.mu.edu!howland.reston.ans.net!plug.news.pipex.net!pipex!tank.news.pipex.net!pipex!news.sprintlink.net!in2.uu.net!harlequin.com!epcot!usenet
From: norvig@meteor.menlo.harlequin.com (Peter Norvig)
Subject: Re: Help
In-Reply-To: Peter Ward's message of Thu, 28 Sep 95 08:41:43 GMT
Message-ID: <NORVIG.95Sep28134822@meteor.menlo.harlequin.com>
Lines: 34
Sender: usenet@harlequin.com (Usenet Maintainer)
Nntp-Posting-Host: meteor.menlo.harlequin.com
Organization: Harlequin Inc, Cambridge, MA
References: <445t0j$skl@umbc9.umbc.edu> <DFKx3r.75z@inesc.pt>
	<812277703snz@mondas.demon.co.uk>
Date: Thu, 28 Sep 1995 20:48:21 GMT


In article <812277703snz@mondas.demon.co.uk> Peter Ward <ward@mondas.demon.co.uk> writes:

> As a naive lisp user I find it useful to see how code is
> optimised for speed/consing. Is I right to assume that the
> additional memory usage of depth2 is because mapcar creates
> a list just to hold the results of the recursive aplication?

Yes, you are right.  Rather than build up the list of results and
apply max to the result, it is better to build up the resulting sum as
you go.  This is done explicitly in the "recursive" solution, and can
also be done by using reduce rather than apply:

(defun depth3 (s)
  (if (atom s) 
      0
      (+ 1 (reduce #'max s :key #'depth3))))

In English, this says "The depth of s is 0 if s is an atom, otherwise
it is one more than the maximum of the depths of the elements of s."
One measure of good style is how closely the English paraphrase of the code
you write matches the English specification of the original problem.

Notes:
(1) Some older implementations of reduce do not support the :key keyword.
(2) (apply fn list) is only guaranteed to work for lists of length up to
    call-arguments-limit, which can be as small as 50.
(3) Versions of depth using reduce and apply fail for arguments like (1 . 2).
(4) Every object is either an atom or a list.
-- 
Peter Norvig                  | Phone: 415-833-4022           FAX: 415-833-4111
Harlequin Inc.                | Email: norvig@harlequin.com
1010 El Camino Real, #310     | http://www.harlequin.com
Menlo Park CA 94025           | http://www.cs.berkeley.edu/~russell/norvig.html
