Re: lisp function questions
- From: "josephoswaldgg@xxxxxxxxxxx" <josephoswald@xxxxxxxxx>
- Date: 29 Sep 2005 19:27:12 -0700
dan655t@xxxxxxxxx wrote:
....
> My other function I am having trouble with is:
> a function that goes through a list and calculates the average of all
> numerica entries that appear somewhere inside the list.
>
> (defun average (m)
> (/ (+ m) (length m))
> )
>
> But I have to only count numeric entries. Also I do not think I am
> taking the sum of the list correctly. Any help would be greatly
> appreciated. Thanks!
Some others have suggested answers to your question, but I believe they
may have missed some essential points in the problem you are supposed
to solve.
First, consider what it means to have an expression (+ a b c)
It works if a, b, and c are variables with numbers as values. I.e., the
function + takes numbers and returns numbers.
What if the value of a, b, or c is not a number, but something like a
string or symbol? The function + does not work on those quantities,
only on numbers. Is m a number in your example?
Secondly, you mention "I have to only count numeric entries." This is
somewhat unusual, but perhaps typical for a introductory exercise. In
particular, by "list" do you mean possibly a list which contains other
lists? And are you supposed to count the numeric entries within the
sublists? Lisp programmers would think of that more as a "tree" than a
simple "list." Some of the answers (such as those using the function
reduce) suggested by others will not work if the list contains
non-numbers.
It seems likely your function is supposed to walk through the tree
structure. For each "leaf" in the tree (i.e. something that is an
"atom"), you should inspect it, to see if it is a number, and if so,
add it to the running sum of numbers you have seen so far. Also, you
should take into account that the number of elements in the sum has
been increased by one. There are a couple ways to do this.
Don't forget to look inside the lists-within-lists, if that is indeed
what your function is supposed to do.
Keep in mind that for problems like you were having with (+ m), you can
experiment at the Lisp prompt with small expressions until you are
comfortable, before you combine these expressions to form a function.
Good luck.
.
- References:
- lisp function questions
- From: dan655t
- lisp function questions
- Prev by Date: Re: A simple interpreter
- Next by Date: Re: lisp function questions
- Previous by thread: Re: lisp function questions
- Next by thread: Where to look for the API documentation?
- Index(es):
Relevant Pages
|