ME Jones <
mark...@shawday.com> writes:
> Hello,
> I am trying to write a function that returns the largest atom in a
> list of any depth. I am very new to lisp and learning.
> I do not want to use the built-in max function
Why? If I had been told not to use max, I'd define a basic 'my-max'
function and use that, since I think the clearest solution uses such a
function. Good Lisp style uses of lots of reusable functions and few
variables.
> and am trying to create a simple function which takes a list of
> integers and returns the largest one. Here is my code so far, any
> help is appreciated, thanks.
>
> ;return the largest value greater than 0 in a list at any level of
> lists of integers.
The test for atoms will include floating-point numbers, rationals,
characters, strings and so on. Of course > is not defined for most of
these, but you are certainly not limited to integers.
> (defun largest_atom(L)
> (cond ((null L) 0)
> ((atom(car L))(cons(car L)(largest_atom(cdr L))))
> (if (< a b)
> b
> a
> )
> )
> )
I would aim to do this without the extra variables a and b, but then I'd
define a max function if prohibited from using max!
And I would also simplify the specification so that
(largest_atom 5) == 5
and to allow for any s-expression so that
(largest_atom '(8 . 9)) == 9
This will allow for a very natural recursive implementation that, if
this is from a tutorial, is likely to be what is wanted. At the very
least, write it using max and then think how you would like to avoid
max.
Spoiler alert -- code outline below. Don't scroll until you've had a
go!
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
(defun largest_atom (l)
(cond ((null l) 0)
((atom l) l)
(t (max <what goes here> <and what goes here?))))
--
Ben.