so far
Code: Select all
(defun odd-count(lst)
(do ((i 0 (+ i 1)
(sum 0))
((>(+ 1 i) (length lst)
(if (oddp lst)
(+ 1 sum)
could somebody help?
[ed note: added "
Code: Select all
" tags - nuntius]
Code: Select all
(defun odd-count(lst)
(do ((i 0 (+ i 1)
(sum 0))
((>(+ 1 i) (length lst)
(if (oddp lst)
(+ 1 sum)
Code: Select all
" tags - nuntius]
Code: Select all
(defun odd-count (lst)
(if (null lst)
0
(+ (if (oddp (first lst)) 1 0)
(odd-count (rest lst)))))
Recursion isn't necessarily "more Lispy". Lisp is a multi-paradigm language, so you can do procedural or OOP if you want. IMO, "idiomatic" Lisp has more to do with transforming code, and building the language from bottom-up so that you can express a solution in whatever language is most suitable to the problem.s-imp wrote:I heard that recursion was a lispy way of doing things, but there could be a better way. I'm not sure if it comes with a performance cost. Perhaps one of the pros can chime in. I'm still trying to get my head around what tail recursion is.
This is true as stated, but can be generalized. To be a bit more precise, a tail call does not have to be a recursive call to the same function. A tail call is any call where the calling function immediately returns after invoking the callee; the return value of the caller is the return value of the callee. In this case, there is little value in setting up a stack frame when invoking the callee; the caller can jump to the callee and whatever value the callee returns is returned to the code that invoked the caller. The great insight around tail calls was that they allowed compilers to optimize with a simple goto/jmp rather than creating stack frames. This means that a function that calls itself from a tail call (tail recursion) will never run out of stack space. The tail call is effectively a loop written in recursive syntax. But this works when you don't call yourself, too.Duke wrote: Tail recursion is when the last call in the function is the function itself. For example, a function that is not tail-recursive might end like this: (cons foo (rec-func (cdr lst)))